package o2o.web.actions.order;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jinyou.utils.common.*;
import com.jinyou.utils.spring.SpringContextHolder;
import jPush.dao.JPushMessage;
import map.HttpRequest;
import notice.dao.NoticeType;
import o2o.cache.agent.AgentOrderOverTimeMemory;
import o2o.cache.agent.CityAgentMemory;
import o2o.cache.agent.ShopAgentRelationMemory;
import o2o.cache.order.*;
import o2o.cache.postman.CityPostmanMemory;
import o2o.cache.postman.PostManLikeMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.shop.ShopStatisticsPreDayMemory;
import o2o.cache.sys.SysCustomerCache;
import o2o.cache.sys.SysVariablePaotuiMemory;
import o2o.cache.user.UserAddressMemory;
import o2o.config.dao.DataDaoSql;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.CityAgent;
import o2o.dao.PO.agent.OrderOverTimeInfo;
import o2o.dao.PO.code.DiscountExchangeCodeInfo;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.game.*;
import o2o.dao.PO.order.*;
import o2o.postman.model.CityPostman;
import o2o.dao.PO.postman.POSTMAN_TYPE;
import o2o.dao.PO.postman.PostManLike;
import o2o.dao.PO.shop.*;
import o2o.dao.PO.sys.SysVariablePaotui;
import o2o.dao.PO.user.UserAddress;
import o2o.dao.VO.order.OrderGoodsVO;
import o2o.service.code.DiscountExchangeCodeService;
import o2o.service.delivery.DeliveryOrderSyncService;
import o2o.service.delivery.to.DeliveryFeeTO;
import o2o.service.delivery.to.DeliveryOrderTO;
import o2o.company.model.ShopInfo;
import o2o.system.data.*;
import o2o.utils.CommonUtils;
import o2o.utils.OrderUtils;
import o2o.utils.RecordsResult;
import o2o.web.actions.divide.CityAgentFeeMan;
import o2o.web.actions.notice.Notice;
import o2o.web.actions.order.thread.OrderThread;
import o2o.web.actions.order.user.UserOrderMan;
import o2o.web.actions.pay.OrderPay;
import o2o.web.actions.sys.GrabOrderModeMan;
import org.apache.commons.lang.StringUtils;

import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.*;

//提交订单管理类
public class SubmitOrderMan {

    //----------------------

    //获取每日订单编号
    static synchronized public int getShopPreDayNo(Long shopId, String ShopOwnUsername, String opUsername) {
        ShopStatisticsPreDay preDay = ShopStatisticsPreDayMemory.getInstance().getByShopId(shopId);
        String today = DateUtils.getCurrentDate();
        if (null != preDay && ValidateUtil.isNotNull(preDay.getPreDay()) && !preDay.getPreDay().equalsIgnoreCase(today)) {
            // 日期非今天的，则重新执行下缓存
            ShopStatisticsPreDayMemory.getInstance().run();
            preDay = ShopStatisticsPreDayMemory.getInstance().getByShopId(shopId);
        }
        if (null == preDay) {
            //没有今天的信息 新建一个
            ShopStatisticsPreDay shopStatistics = new ShopStatisticsPreDay(shopId, ShopOwnUsername, 1, 0d, today, opUsername, DateUtils.getCurrTime());
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.SHOP_STATISTICS_PRE_DAY, shopStatistics);
            } catch (SQLException e) {
                e.printStackTrace();
                return 0;
            }

            ShopStatisticsPreDayMemory.getInstance().updateByShopId(shopId);
            preDay = ShopStatisticsPreDayMemory.getInstance().getByShopId(shopId);
        } else {
            StringBuffer sb = new StringBuffer();
            sb.append("update ").append(PojoTables.SHOP_STATISTICS_PRE_DAY).append(" set orderCounts = IFNULL(orderCounts,0)+1 ,updateUser = '").append(opUsername)
                    .append("' where shopId = ").append(shopId).append(" and delFlag = 0 and preDay = '").append(today).append("'");
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return 0;
            }

            ShopStatisticsPreDayMemory.getInstance().updateByShopId(shopId);
            preDay = ShopStatisticsPreDayMemory.getInstance().getByShopId(shopId);
        }

        if (null == preDay) {
            return 0;
        }

        return preDay.getOrderCounts();
    }

    //订单提交处理
    public static OrderSubmitResult submitOrder(String sysAppKey, String appFlag,
                                                String submitUsername, Long shopId,
                                                Integer orderType,
                                                String shareUsername,
                                                Long deliveryId,
                                                Double deliveryPrice, Double packetPrice, Integer canJuCount, //配送费、打包费、餐具套数
                                                Integer isUrgent,
                                                String goodsInfoJson,
                                                Integer isZiQu, // 0 配送 1自取 2 到店堂食(无打包配送费) 3直邮
                                                Integer isAppointment, Long ziQuTime,
                                                String shopSpecs,
                                                String buyName, String buyPhone,
                                                Double buyLat, Double buyLng, String buyProvince, String buyCity, String buyCounty, String buyAddress, String buyAddress2, String buyAddress3,
                                                String note,
                                                Long gameId, Long gameRuleId,
                                                String gameInfoJson,
                                                String redpacketJson,
                                                Double tipMoney,
                                                Double taxMoney,
                                                Integer isUnderLinePay, Long integral,
                                                Integer likePostmanAdvance,
                                                Integer isGroupOrder, Integer isFlashSaleOrder, Double ridingDistance,
                                                Double tipRate, Long vipPacketGameId, Integer useVipPacket, Integer isDisCountOrder, String exchangeCode) {   // 小费比例
        return submitOrder(sysAppKey, appFlag,
                submitUsername, shopId,
                orderType,
                null,//支付订单编号
                shareUsername,
                deliveryId,
                deliveryPrice, packetPrice, canJuCount,
                isUrgent,
                goodsInfoJson,
                isZiQu, isAppointment, ziQuTime,
                shopSpecs,
                buyName, buyPhone,
                buyLat, buyLng, buyProvince, buyCity, buyCounty, buyAddress, buyAddress2, buyAddress3,
                note,
                gameId, gameRuleId,
                gameInfoJson, redpacketJson, tipMoney, taxMoney, isUnderLinePay, integral, likePostmanAdvance,
                isGroupOrder, isFlashSaleOrder, ridingDistance, tipRate, vipPacketGameId, useVipPacket, isDisCountOrder, exchangeCode);
    }

    //订单提交处理
    public static OrderSubmitResult submitOrder(String sysAppKey, String appFlag,
                                                String submitUsername, Long shopId,
                                                Integer orderType,
                                                String shareUsername,
                                                Long deliveryId,
                                                Double deliveryPrice, Double packetPrice, Integer canJuCount, //配送费、打包费、餐具套数
                                                Integer isUrgent,
                                                String goodsInfoJson,
                                                Integer isZiQu, // 0 配送 1自取 2 到店堂食(无打包配送费) 3直邮
                                                Integer isAppointment, Long ziQuTime,
                                                String shopSpecs,
                                                String buyName, String buyPhone,
                                                Double buyLat, Double buyLng, String buyProvince, String buyCity, String buyCounty, String buyAddress, String buyAddress2, String buyAddress3,
                                                String note,
                                                Long gameId, Long gameRuleId,
                                                String gameInfoJson,
                                                String redpacketJson,
                                                Double tipMoney,
                                                Double taxMoney,
                                                Integer isUnderLinePay, Long integral,
                                                Integer likePostmanAdvance) {
        return submitOrder(sysAppKey, appFlag,
                submitUsername, shopId,
                orderType,
                null,//支付订单编号
                shareUsername,
                deliveryId,
                deliveryPrice, packetPrice, canJuCount,
                isUrgent,
                goodsInfoJson,
                isZiQu, isAppointment, ziQuTime,
                shopSpecs,
                buyName, buyPhone,
                buyLat, buyLng, buyProvince, buyCity, buyCounty, buyAddress, buyAddress2, buyAddress3,
                note,
                gameId, gameRuleId,
                gameInfoJson, redpacketJson, tipMoney, taxMoney, isUnderLinePay, integral, likePostmanAdvance, 0, 0,
                0.0d, null, null, null, null, null);
    }


    private static OrderSubmitResult submitOrder(String sysAppKey, String appFlag,
                                                 String submitUsername, Long shopId,
                                                 Integer orderType,
                                                 String payOrderNo,
                                                 String shareUsername,
                                                 Long deliveryId,
                                                 Double deliveryPrice, Double packetPrice, Integer canJuCount, //配送费、打包费、餐具套数
                                                 Integer isUrgent,
                                                 String goodsInfoJson,
                                                 Integer isZiQu, Integer isAppointment, Long ziQuTime,// 0 配送 1自取 2 到店堂食(无打包配送费) 3直邮
                                                 String shopSpecs,
                                                 String buyName, String buyPhone,
                                                 Double buyLat, Double buyLng, String buyProvince, String buyCity, String buyCounty, String buyAddress, String buyAddress2, String buyAddress3,
                                                 String note,
                                                 Long gameId, Long gameRuleId,
                                                 String gameInfoJson,
                                                 String redpacketJson,
                                                 Double tipMoney,
                                                 Double taxMoney,
                                                 Integer isUnderLinePay, // 线下支付？
                                                 Long integral,
                                                 Integer likePostmanAdvance,
                                                 Integer isGroupOrder,
                                                 Integer isFlashSaleOrder,
                                                 Double distance,
                                                 Double tipRate,
                                                 Long vipPacketGameId,
                                                 Integer useVipPacket,
                                                 Integer isDisCountOrder,
                                                 String exchangeCode
    ) {
        OrderSubmitResult orderSubmitResult = new OrderSubmitResult();
        // 积分订单
        Integer isFreeGood = 0; //
        if (isDisCountOrder == null || isDisCountOrder != 1) {
            isDisCountOrder = 0;
        }
        boolean isIntegralOrder = false;
        if (null != orderType) {
            switch (orderType) {
                case ORDER_TYPE.INTEGRAL_ORDER: {//积分兑换订单
                    List<ShopInfo> list = ShopMemory.getInstance().listOfIntegralShop(SHOP_IS_INTEGRAL.HAS_INTEGRAL_SHOP);
                    ShopInfo shopInfo = null;

                    if (!ValidateUtil.isAbsList(list)) {
                        orderSubmitResult.setSuccess(false);
                        orderSubmitResult.setError("没有该商城");
                        return orderSubmitResult;
                    } else {
                        shopInfo = list.get(0);
                    }
                    if (shopInfo == null) {
                        orderSubmitResult.setSuccess(false);
                        orderSubmitResult.setError("没有该商城");
                        return orderSubmitResult;
                    } else {
                        shopId = shopInfo.getId();
                        isIntegralOrder = true;
                    }
                    if (ValidateUtil.isNull(buyCity)) {
                        orderSubmitResult.setSuccess(false);
                        orderSubmitResult.setError("城市不能为空");
                        return orderSubmitResult;
                    }
                    if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {//多语言版
                        if (ValidateUtil.isNotNull(buyCity)) {
                            buyCity = JYPinyinHelper.isChinese(buyCity) ? JYPinyinHelper.toHanyuPinyin(buyCity) : buyCity.toLowerCase();
                        }
                    }
                }
                break;
            }
        }

        // 积分订单没有预约时间
        if (!isIntegralOrder && null != isAppointment && 0 == 1 - isAppointment && (null == ziQuTime || ziQuTime < 1)) {
            orderSubmitResult.setSuccess(false);
            orderSubmitResult.setError("请先选择预约时间");
            return orderSubmitResult;
        }

        //店铺信息
        ShopInfo shopInfo = null;
        if (null != shopId && shopId > 0) {
            shopInfo = ShopMemory.getInstance().getShopById(shopId);

            if (null == shopInfo) {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("当前店铺已不存在，请核对后重试");
                return orderSubmitResult;
            }
            // 判断商家
            if (shopInfo.getCloudShopType() != null && (shopInfo.getCloudShopType() & CLOUD_SHOP_TYPE.CLOUD_SHOP_TYPE_SQUARE) > 0) {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("当前为创业广场商家,无法提交普通外卖订单");
                return orderSubmitResult;
            }
//
//            //判断预约时间
//            OrderSubmitResult result = checkAppointmentTime(isAppointment, ziQuTime, shopInfo);// 外卖订单
//            if (null == result) {
//                orderSubmitResult.setSuccess(false);
//                orderSubmitResult.setError("预约时间有误，请重新选择");
//                return orderSubmitResult;
//            } else {
//                if (!result.isSuccess()) {
//                    return result;
//                }
//            }
        }
        deliveryPrice = 0d;

        // 积分兑换商品不在验证用户的地理位置和活动等信息
        Long agentId = null;
        UserAddress userAddress = UserAddressMemory.getInstance().getAddressInfo(deliveryId);
        if (!isIntegralOrder) {
            //订单对应的代理信息
            agentId = ShopAgentRelationMemory.getInstance().getAgentByShopId(shopId);
            CityAgent cityAgent = null;
            if (SYS_SETTINGS.SHOP_BELONG_MULTIPLE_AGENT == 1) {

            } else {
                if (ValidateUtil.isNotID(agentId)) {
                    cityAgent = CityAgentMemory.getInstance().getByUsername(shopInfo.getOwnUsername());
                    if (null == cityAgent) {
                        //如果配送员配送是按商圈划分的 那么提交订单必须要商圈信息
                        if (ValidateUtil.isAbsInteger(SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT) && (0 == POSTMAN_IN_CITY_OR_AGENT_DATA.AGENT - SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT || 0 == POSTMAN_IN_CITY_OR_AGENT_DATA.FREE_AGENT - SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT)) {
                            if (null != isZiQu && 0 == isZiQu) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("当前店铺信息有误，请联系客服[该店铺没有管理代理信息]");
                                return orderSubmitResult;
                            }
                        }
                    } else {
                        agentId = cityAgent.getId();
                    }
                } else {
                    cityAgent = CityAgentMemory.getInstance().getById(agentId);
                }
            }

            if (ValidateUtil.isNotID(deliveryId) && ValidateUtil.isNotAbsInteger(isZiQu)) {
                if (ValidateUtil.isNotLatLng(buyLat, buyLng) || ValidateUtil.isNull(buyCity) || ValidateUtil.isNull(buyAddress)) {
                    orderSubmitResult.setSuccess(false);
                    orderSubmitResult.setError("请选择收货地址");
                    return orderSubmitResult;
                }
            }
            //配送费处理
            if (null != isZiQu && 0 == isZiQu) { //需要配送
                if (ValidateUtil.isID(deliveryId)) {//配送
                    if (null == userAddress) {
                        orderSubmitResult.setSuccess(false);
                        orderSubmitResult.setError("请核对送货地址后重试");
                        return orderSubmitResult;
                    }
                }

                if (SYS_SETTINGS.SHOP_BELONG_MULTIPLE_AGENT == 1) {
                    List<Long> agentIdList = ShopAgentRelationMemory.getInstance().agentListOfShopId(shopId);
                    if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && (0 == 1 - SYS_SETTINGS.IS_ELECTRONIC_FENCE || 0 == 2 - SYS_SETTINGS.IS_ELECTRONIC_FENCE)) {
                        orderSubmitResult = doDeliveryPriceV2(isZiQu, shopInfo,
                                userAddress, agentId,
                                cityAgent, deliveryPrice,
                                buyLat, buyLng,
                                agentIdList,
                                distance,
                                orderSubmitResult);
                    } else {
                        orderSubmitResult = doDeliveryPrice(isZiQu, shopInfo,
                                userAddress, agentId,
                                cityAgent, deliveryPrice,
                                buyLat, buyLng,
                                distance,
                                orderSubmitResult);
                    }
                } else {
                    if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && (0 == 1 - SYS_SETTINGS.IS_ELECTRONIC_FENCE || 0 == 2 - SYS_SETTINGS.IS_ELECTRONIC_FENCE)) {
                        orderSubmitResult = doDeliveryPriceV2(isZiQu, shopInfo,
                                userAddress, agentId,
                                cityAgent, deliveryPrice,
                                buyLat, buyLng,
                                distance,
                                orderSubmitResult);
                    } else {
                        orderSubmitResult = doDeliveryPrice(isZiQu, shopInfo,
                                userAddress, agentId,
                                cityAgent, deliveryPrice,
                                buyLat, buyLng,
                                distance,
                                orderSubmitResult);
                    }
                }
                if (null != orderSubmitResult) {
                    if (orderSubmitResult.isSuccess()) {
                        if (ValidateUtil.isID(orderSubmitResult.getAgentId())) {
                            agentId = orderSubmitResult.getAgentId();
                        }
                        deliveryPrice = orderSubmitResult.getOrderDeliveryPrice();
                        if (ValidateUtil.isAbsDouble(orderSubmitResult.getDistance())) {
                            distance = JYMathDoubleUtils.scaleHalfUp(JYMathDoubleUtils.div(orderSubmitResult.getDistance(), 1000));
                        }
                    } else {
                        return orderSubmitResult;
                    }
                } else {
                    orderSubmitResult.setSuccess(false);
                    orderSubmitResult.setError("验证配送费错误，请稍后再试");
                    return orderSubmitResult;
                }
            }
            if (ValidateUtil.isID(gameId) && ValidateUtil.isID(gameRuleId) && ValidateUtil.isNotNull(gameInfoJson)) {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("提交的活动信息有误，请重新选择");
                return orderSubmitResult;
            }
        }

        //验证店铺有效性
        if (ShopMemory.getInstance().notExist(shopId)) {
            orderSubmitResult.setSuccess(false);
            orderSubmitResult.setError("当前店铺不存在，请刷新后重试");
            return orderSubmitResult;
        }

        if (ValidateUtil.isNull(goodsInfoJson)) {
            orderSubmitResult.setSuccess(false);
            orderSubmitResult.setError("请先选购商品");
            return orderSubmitResult;
        }


        if (!isIntegralOrder && ValidateUtil.isAbsInteger(isZiQu) && 0 == ZI_QU_TYPE.ZI_QU - isZiQu) {
            if (ValidateUtil.isNull(buyName) || ValidateUtil.isNull(buyPhone)) {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("请输入姓名及手机号，以方便店家联系您确认信息");
                return orderSubmitResult;
            }
        }

        // 积分订单不用检测
        //店铺是否已打烊
        if (!isIntegralOrder && 0 != 1 - shopInfo.getIsWork()) {
            if (isAppointment != null && 0 == 1 - isAppointment && 0 == 1 - shopInfo.getIsAppointment()) {
                //预约订单不需要检查店铺是否已打烊
                //todo  需要验证配送时间是否在可预约时间内
            } else {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("店铺已打烊");
                return orderSubmitResult;
            }
        }

        // 积分兑换不检测 配送方式
        if (!isIntegralOrder) {
            if (null != isZiQu) {
                switch (isZiQu) {
                    case ZI_QU_TYPE.PEI_SONG: {
                        if (0 == shopInfo.getIsPeiSong()) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("该店铺不支持配送");
                            return orderSubmitResult;
                        }
                    }
                    break;
                    case ZI_QU_TYPE.TANG_SHI:
                    case ZI_QU_TYPE.ZI_QU: {
                        if (0 == shopInfo.getIsDaoDian()) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("该店铺不支持到店消费");
                            return orderSubmitResult;
                        }
                    }
                    break;
                }
            }
        }
        //打包费
        if (!isIntegralOrder && null != shopInfo && null != shopInfo.getPacketPrice()) {
            packetPrice = shopInfo.getPacketPrice();
        } else {
            packetPrice = 0d;
        }

        //加急配送费
        Double urgentPrice = 0d;
        if (!isIntegralOrder && null != SYS_SETTINGS.URGENT_DELIVERY_PRICE) {
            urgentPrice = Double.parseDouble(SYS_SETTINGS.URGENT_DELIVERY_PRICE + "");
        }
        if (ValidateUtil.isNotAbsInteger(isUrgent)) {
            isUrgent = 0;
        }

        //验证配送费
        if (!isIntegralOrder && ValidateUtil.isAbsInteger(isZiQu) && 0 == isZiQu) { //配送的才去验证   0配送  1自取
            //配送费计算方式
            if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 2 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {//配送费计算方式 1固定配送费 2按距离计算 3. 按距离（店铺）
                //按距离(平台)计算，验证收货地址时已经验证过了
            } else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 3 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {//配送费计算方式 1固定配送费 2按距离计算 3. 按距离（店铺）
                //按距离（店铺）计算，验证收货地址时已经验证过了
            } else {
                deliveryPrice = shopInfo.getYunfei();
            }

            // 积分兑换
            //添加加急费
            if (!isIntegralOrder && 0 == 1 - isUrgent) {//如果是加急
                deliveryPrice = JYMathDoubleUtils.add(urgentPrice, deliveryPrice);
            }
        }

        //1. 生成订单编号
        String orderNo = OrderUtils.getOrderNo();
        Long time = DateUtils.getCurrTime();
        OrderInfo orderInfo = new OrderInfo();
        if (ValidateUtil.isAbsDouble(distance)) {
            orderInfo.setDistance(distance);
        }
        if (!isIntegralOrder) {
            // 处理超时时间
            OrderOverTimeInfo agentOrderOverTimeInfo = null;
            if (ValidateUtil.isID(agentId)) {
//            OrderOverTimeInfo agentOrderOverTimeInfo = AgentOrderOverTimeMemory.getInstance().getAgentOrderOverTimeInfoByAgentId(agentId);
                agentOrderOverTimeInfo = AgentOrderOverTimeMemory.getInstance().getAgentOrderOverTimeInfoByAgentId(agentId);
                if (null == agentOrderOverTimeInfo) {
                    agentOrderOverTimeInfo = AgentOrderOverTimeMemory.getInstance().getPlateDefaultSetting();
                }
                if (null != agentOrderOverTimeInfo) {
                    Integer appointShopTime = agentOrderOverTimeInfo.getAppointShopTime();
                    Integer appointPostmanTime = agentOrderOverTimeInfo.getAppointPostmanTime();
                    orderInfo.setAgentPostmanOverTime(agentOrderOverTimeInfo.getPostmanOverTime());
                    orderInfo.setAgentShopOverTime(agentOrderOverTimeInfo.getShopOverTime());
//                    orderInfo.setAgentOrderOverTime(agentOrderOverTimeInfo.getOrderOverTime());
                    orderInfo.setAgentOrderOverTime(calculateOrderPsTime(agentOrderOverTimeInfo, distance));
                    orderInfo.setAgentNotTakenOrderTime(agentOrderOverTimeInfo.getNotTakenOrderTime());
                    orderInfo.setAgentPostmanAdvanceTime(agentOrderOverTimeInfo.getPostmanAdvanceTime());
                    orderInfo.setAgentAppointPostmanTime(appointPostmanTime);
                    orderInfo.setAlertOrderTime(agentOrderOverTimeInfo.getAlertOrderTime());
                    orderInfo.setAlertPostmanTime(agentOrderOverTimeInfo.getAlertPostmanTime());
                    orderInfo.setPostmanBackOrderTime(agentOrderOverTimeInfo.getPostmanBackOrderTime());
//                // 处理期望送达时间
//                // 如果超出配置的预计送达时间，则处理为预约单
//                if ((null == isAppointment || 0 == isAppointment) && ValidateUtil.isAbsLong(orderInfo.getZiQuTime())
//                        && ((ValidateUtil.isAbsInteger(appointShopTime) && appointShopTime > 0) || (ValidateUtil.isAbsInteger(appointPostmanTime) && appointPostmanTime > 0))) {
//                    Long zz = orderInfo.getZiQuTime() - time;
//                    if (ValidateUtil.isAbsLong(zz) && zz > 0) {
//                        if ((ValidateUtil.isAbsInteger(appointShopTime) && appointShopTime > 0 && zz > (appointShopTime * 60 * 1000))
//                                || (ValidateUtil.isAbsInteger(appointPostmanTime) && appointPostmanTime > 0 && zz > (appointPostmanTime * 60 * 1000)))
//                            orderInfo.setIsAppointment(1);
//                    }
//                }
                }
            }
            // 处理是否预约
            OrderSubmitResult result = checkAppointmentTime(isAppointment, ziQuTime, shopInfo, agentOrderOverTimeInfo);// 外卖订单
            if (null == result) {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("预约时间有误，请重新选择");
                return orderSubmitResult;
            } else {
                if (!result.isSuccess()) {
                    return result;
                } else {
                    orderInfo.setIsAppointment(result.getIsAppointment());
                }
            }
        }



        //商品信息
        int totalCount = 0;
        double totalMoney = 0;//订单总金额
        double totalWeight = 0;//商品总重量
        double totalPacketPrice = 0;
        double taxMoneyV1 = 0;
        long totalIntegral = 0;
        boolean hasUsedZhekou = false;//是否已经使用过折扣（商品现价比原价少）




        // 陈鲜生  商品重量参与配送费计算
        if (SYS_SETTINGS.IS_WEIGHT_ADD_DELIVERY != null && SYS_SETTINGS.IS_WEIGHT_ADD_DELIVERY == 1) {
            // 重量参与配送费计算
            orderSubmitResult = doOrderWeightDeliveryPrice(isZiQu, totalWeight, deliveryPrice, shopInfo, agentId, orderSubmitResult);
            if (null != orderSubmitResult) {
                if (orderSubmitResult.isSuccess()) {
                    deliveryPrice = orderSubmitResult.getOrderDeliveryPrice();
                } else {
                    return orderSubmitResult;
                }
            }
        }
        //是否满足起送费
        if (!isIntegralOrder && (0 == isZiQu || 0 == ZI_QU_TYPE.ZHI_YOU - isZiQu)) { //配送的才去验证
            if (ValidateUtil.isAbsDouble(shopInfo.getStartFree()) && totalMoney < shopInfo.getStartFree()) {
                rollBackGoods(orderNo);
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("不满足起送费要求：" + shopInfo.getStartFree());
                return orderSubmitResult;
            }
        }

        if (null != isZiQu) {
            if (0 == ZI_QU_TYPE.TANG_SHI - isZiQu) {
                //  堂食不收配送费
                deliveryPrice = 0d;
                packetPrice = 0d;
            } else if (0 == ZI_QU_TYPE.ZHI_YOU - isZiQu) {
                // 直邮收取固定配送费
                if (null != shopInfo) {
                    deliveryPrice = shopInfo.getYunfei();
                }
            }
        }

        orderInfo.setIsGroupOrder(isGroupOrder);
        orderInfo.setIsFlashSaleOrder(isFlashSaleOrder);
        orderInfo.setOrderStatus(ORDER_STATUS.SUBMIT);
        if (null == orderType) {
            orderType = ORDER_TYPE.SHOP_GOODS;
        }
        orderInfo.setOrderType(orderType);//订单类型，商城订单
        orderInfo.setOrderNo(orderNo);
        orderInfo.setCreateTime(time);
        orderInfo.setCreateUser(submitUsername);
        orderInfo.setTotalWeight(totalWeight);
        orderInfo.setAgentId(agentId);

        orderInfo.setIsSeriesSaleShop(shopInfo.getIsSeriesSale() == null ? 0 : shopInfo.getIsSeriesSale());// 商家类型

        orderInfo.setShopId(shopId);
        orderInfo.setUsername(submitUsername);
        orderInfo.setIsComment(0);//是否已评价
        orderInfo.setUserDel(0);//是否已删除 0未删，1删除

        orderInfo.setIsUrgent(isUrgent);//是否加急
        orderInfo.setNote(note);//订单备注


        //店铺配送方式
        if (null != shopInfo && null != shopInfo.getIsSelfPost()) {
            orderInfo.setShopSelfPost(shopInfo.getIsSelfPost());
        }

        //订单金额
        orderInfo.setTotalCount(totalCount); //购买数量(几件商品)
        if (!isIntegralOrder) {
            orderInfo.setTotalGoodsMoney(totalMoney); //商品总金额
            totalMoney = JYMathDoubleUtils.add(totalMoney, packetPrice);//订单总金额加上店铺打包费
            totalMoney = JYMathDoubleUtils.add(totalMoney, totalPacketPrice);//订单总金额加上每个商品打包费c
        } else {
            // 积分兑换商品
            orderInfo.setIntegral(totalIntegral);
        }

        orderInfo.setOriginalYunFei(deliveryPrice);
        //V2 满足金额减配送费（非免配送费）
        if (!isIntegralOrder && null != shopInfo && ValidateUtil.isAbsDouble(shopInfo.getFreeYunFei()) && SYS_SETTINGS.ZHEKOU_NOT_JOIN_FEE_YUNFEI != 1) {
            if (JYMathDoubleUtils.sub(shopInfo.getFreeYunFei(), totalMoney) <= 0) {
                //记录原始配送费及店铺减免配送费部分金额
                orderInfo.setOriginalYunFei(deliveryPrice);
                orderInfo.setOriginalYunFeiShop(shopInfo.getFreeYunFeiShop());
                if (null != shopInfo.getFreeYunFeiShop() && null != shopInfo.getFreeYunFeiMoney()
                        && 0 == -1 - shopInfo.getFreeYunFeiMoney() && -1 - shopInfo.getFreeYunFeiShop() == 0) {
                    orderInfo.setOriginalYunFeiShop(deliveryPrice);
                }

                //设置本订单实际收取的配送费
                if (null != shopInfo.getFreeYunFeiMoney()) {
                    Double freeMoney = 0d;
                    if (0 == -1 - shopInfo.getFreeYunFeiMoney()) {
                        //免配送费
                        freeMoney = deliveryPrice;
                        deliveryPrice = 0d;
                    } else {
                        //减配送费
                        freeMoney = deliveryPrice;
                        deliveryPrice = JYMathDoubleUtils.sub(deliveryPrice, shopInfo.getFreeYunFeiMoney());
                        if (deliveryPrice < 0) {
                            deliveryPrice = 0d;
                        } else {
                            freeMoney = shopInfo.getFreeYunFeiMoney();
                        }
                    }
                    if (null != shopInfo.getFreeYunFeiShop() && null != shopInfo.getFreeYunFeiMoney()
                            && 0 == -1 - shopInfo.getFreeYunFeiMoney() && -1 - shopInfo.getFreeYunFeiShop() == 0) {
                        // orderInfo.setOriginalYunFeiShop(deliveryPrice);
                    } else {
                        // 减免的配送费 要大于或等于 店铺承担的
                        if (JYMathDoubleUtils.sub(freeMoney, shopInfo.getFreeYunFeiShop()) < 0) {
                            orderInfo.setOriginalYunFeiShop(freeMoney);
                        }
                    }
                }
            }
        }
        // // 计算价格问题
        if (isFreeGood != null && isFreeGood == 1) {
            deliveryPrice = 0.0d;
        }
        totalMoney = JYMathDoubleUtils.add(totalMoney, deliveryPrice);//订单总金额加上配送费
        orderInfo.setTotalPrice(totalMoney);//订单总金额
        orderInfo.setDeliveryPrice(deliveryPrice);//配送费
        orderInfo.setPacketPrice(JYMathDoubleUtils.add(packetPrice, totalPacketPrice));//店铺打包费+每个商品的

        String shopCity = shopInfo.getCity();
        if (ValidateUtil.isNotNull(shopCity)) {
            if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {
                if (JYPinyinHelper.isChinese(shopCity)) {
                    shopCity = JYPinyinHelper.toHanyuPinyin(shopCity);
                } else {
                    shopCity = shopCity.toLowerCase();
                }
            }
        }
        // 是不是使用哒哒配送
        if (SYS_SETTINGS.IS_OTHER_POST == 2) {
            orderInfo.setIsOtherPost(1);
        }
        orderInfo.setShopName(shopInfo.getShopName());//店铺名称
        orderInfo.setShopNameLang(shopInfo.getShopNameLang());// 店铺多语言
        orderInfo.setShopPhone(shopInfo.getTelephone());//店铺电话
        orderInfo.setShopCity(shopCity);//店铺所在城市
        orderInfo.setShopAddress(shopInfo.getAddress());//店铺地址
        orderInfo.setShopLat(shopInfo.getLat());//店铺纬度
        orderInfo.setShopLng(shopInfo.getLng());//店铺经度
        String shopImage = shopInfo.getImageUrl();
        if (ValidateUtil.isNetUrl(shopImage)) {
            shopImage = shopImage.replace(SYS_CONFIG_PATH.IMAGE_BASE_URL, "");
        }
        orderInfo.setShopImageUrl(shopImage);//店铺头像

        //配送信息
        if (ValidateUtil.isAbsInteger(isZiQu) && (0 == ZI_QU_TYPE.PEI_SONG - isZiQu || 0 == ZI_QU_TYPE.ZHI_YOU - isZiQu)) { //配送
            if (ValidateUtil.isID(deliveryId)) { //选择的收货地址
                orderInfo.setDeliveryId(deliveryId);
                if (null == userAddress) {
                    rollBackGoods(orderNo);
                    orderSubmitResult.setSuccess(false);
                    orderSubmitResult.setError("请核对送货地址后重试");
                    return orderSubmitResult;
                }
                orderInfo.setBuyer(userAddress.getBuyer());
                orderInfo.setTelephone(userAddress.getTelephone());
                String address = "";
                if (ValidateUtil.isNotNull(userAddress.getAddress())) {
                    address = userAddress.getAddress();
                }
                if (ValidateUtil.isNotNull(userAddress.getAddress2()) && !"null".equalsIgnoreCase(userAddress.getAddress2())) {
                    address += " " + userAddress.getAddress2();
                }
                if (ValidateUtil.isNotNull(userAddress.getAddress3()) && !"null".equalsIgnoreCase(userAddress.getAddress3())) {
                    address += " " + userAddress.getAddress3();
                }
                if (ValidateUtil.isNotNull(userAddress.getExtra1()) && !"null".equalsIgnoreCase(userAddress.getExtra1())) {
                    address += " " + userAddress.getExtra1();
                }
                if (ValidateUtil.isNotNull(userAddress.getExtra2()) && !"null".equalsIgnoreCase(userAddress.getExtra2())) {
                    address += " " + userAddress.getExtra2();
                }
                if (ValidateUtil.isNotNull(userAddress.getExtra3()) && !"null".equalsIgnoreCase(userAddress.getExtra3())) {
                    address += " " + userAddress.getExtra3();
                }
                orderInfo.setAddress(address);
                String address2 = "";
                if (ValidateUtil.isNotNull(userAddress.getAddress2()) && !"null".equalsIgnoreCase(userAddress.getAddress2())) {
                    address2 = userAddress.getAddress2();
                }
                if (ValidateUtil.isNotNull(userAddress.getAddress3()) && !"null".equalsIgnoreCase(userAddress.getAddress3())) {
                    address2 += " " + userAddress.getAddress3();
                }
                orderInfo.setAddress2(address2);
                orderInfo.setLng(userAddress.getLng());
                orderInfo.setLat(userAddress.getLat());
                orderInfo.setProvince(userAddress.getProvince());
                orderInfo.setCity(userAddress.getCity());
                orderInfo.setCounty(userAddress.getCounty());
                orderInfo.setAgentAddressId(userAddress.getAgentAddressId());   // 楼号
            } else {//填写的收货地址
                orderInfo.setBuyer(buyName);
                orderInfo.setTelephone(buyPhone);
                String address = "";
                if (ValidateUtil.isNotNull(buyAddress)) {
                    address = buyAddress;
                }
                if (ValidateUtil.isNotNull(buyAddress2)) {
                    address += buyAddress2;
                }
                if (ValidateUtil.isNotNull(buyAddress3)) {
                    address += buyAddress3;
                }
                orderInfo.setAddress(address);
                String address2 = "";
                if (ValidateUtil.isNotNull(buyAddress2)) {
                    address2 += buyAddress2;
                }
                if (ValidateUtil.isNotNull(buyAddress3)) {
                    address2 += buyAddress3;
                }
                orderInfo.setAddress2(address2);
                orderInfo.setLng(buyLng);
                orderInfo.setLat(buyLat);
                orderInfo.setProvince(buyProvince);
                orderInfo.setCity(buyCity);
                orderInfo.setCounty(buyCounty);
            }
        }

        //自取或到店消费类  保存用户姓名及手机号
        if (ValidateUtil.isAbsInteger(isZiQu) && (0 == ZI_QU_TYPE.ZI_QU - isZiQu || 0 == ZI_QU_TYPE.TANG_SHI - isZiQu)) {
            orderInfo.setBuyer(buyName);
            orderInfo.setTelephone(buyPhone);
            orderInfo.setCity(shopInfo.getCity()).setCounty(shopInfo.getCounty());
        }
        if (!isIntegralOrder) {
            orderInfo.setIsZiQu(isZiQu);
        }
//        // todo 苹果更新后需要删除（苹果提交订单了2020年）
//        if (null != ziQuTime && ziQuTime > 1601346545000l) {
//            ziQuTime = ziQuTime - 31622400000l;
//        }
        orderInfo.setZiQuTime(ziQuTime);
//        //预约单
//        if (null != isAppointment) {
//            orderInfo.setIsAppointment(isAppointment);
//        }

        Double integralOffsetMoney = 0.0d;
        Double mustPayMoney = totalMoney;//必须支付金额
        Double awardMoney = 0d;//奖励金额
        Double platformAwardMoney = 0d;//平台奖励金额
        Double shopAwardMoney = 0d;//店铺奖励金额
        Double cityAdminAwardMoney = 0.0d;// 代理奖励金额
        orderInfo.setAwardMoney(awardMoney);
        orderInfo.setPlatformAwardMoney(platformAwardMoney);
        orderInfo.setShopAwardMoney(shopAwardMoney);
        orderInfo.setTotalPrice(mustPayMoney);//待支付金额
        orderInfo.setTotalMoney(totalMoney);//订单总金额
        // 计算vip
        RedPacketGame vipPacketGame = null;
        if (!isIntegralOrder) {
            if (null == SYS_SETTINGS.AWARD_AND_SALE_MODEL) {
                orderInfo = doOrderGame(submitUsername, shopInfo, gameId, gameRuleId, gameInfoJson,
                        orderNo, orderInfo,
                        time, totalMoney, orderSubmitResult);
                if (null == orderInfo) {
                    orderSubmitResult.setSuccess(false);
                    orderSubmitResult.setError("活动解析错误，请稍后再试.");
                    return orderSubmitResult;
                }
                awardMoney = orderInfo.getAwardMoney();
                mustPayMoney = orderInfo.getTotalPrice();
                platformAwardMoney = orderInfo.getPlatformAwardMoney();
                shopAwardMoney = orderInfo.getShopAwardMoney();
            } else {
                switch (SYS_SETTINGS.AWARD_AND_SALE_MODEL) {
                    case 0: { //0满减和折扣能够同时使用
                        orderInfo = doOrderGame(submitUsername, shopInfo, gameId, gameRuleId, gameInfoJson,
                                orderNo, orderInfo,
                                time, totalMoney, orderSubmitResult);
                        if (null == orderInfo) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("活动解析错误，请稍后再试.");
                            return orderSubmitResult;
                        }
                        awardMoney = orderInfo.getAwardMoney();
                        mustPayMoney = orderInfo.getTotalPrice();
                        platformAwardMoney = orderInfo.getPlatformAwardMoney();
                        shopAwardMoney = orderInfo.getShopAwardMoney();
                    }
                    break;
                    case 1: { //1只能使用折扣
                        //不在处理满减活动
                        if (hasUsedZhekou) {//已经使用改过折扣

                        } else {
                            orderInfo = doOrderGame(submitUsername, shopInfo, gameId, gameRuleId, gameInfoJson,
                                    orderNo, orderInfo,
                                    time, totalMoney, orderSubmitResult);
                            if (null == orderInfo) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("活动解析错误，请稍后再试.");
                                return orderSubmitResult;
                            }
                            awardMoney = orderInfo.getAwardMoney();
                            mustPayMoney = orderInfo.getTotalPrice();
                            platformAwardMoney = orderInfo.getPlatformAwardMoney();
                            shopAwardMoney = orderInfo.getShopAwardMoney();
                        }
                    }
                    break;
                    case 2: {//2只能使用满减
                        //todo 商品处理为原价
                    }
                    break;
                    case 3: {//3根据用户选择其一处理
                        //todo 待处理
                    }
                    break;
                    default: {
                    }
                    break;
                }
            }


            if (ValidateUtil.isID(vipPacketGameId) && useVipPacket != null && useVipPacket == 1 && SYS_SETTINGS.HAS_MEMBER_RECHARGE == 1) {
            } else {
            }

            // todo: 计算自取的折扣问题
            if (SYS_SETTINGS.HAS_ZIQU_AWARD == 1 && isZiQu == 1 && orderType - ORDER_TYPE.SHOP_GOODS == 0 && shopInfo != null && ValidateUtil.isAbsDouble(shopInfo.getZiQuAwardRate())) {
                double ziquAwardMoney = 0.0d;
                // 折扣金额
                if (shopInfo.getZiQuAwardRate() > 100) {
                    // 优惠超过100 不在进行处理
                } else {
                    ziquAwardMoney = JYMathDoubleUtils.mul(mustPayMoney, JYMathDoubleUtils.div(shopInfo.getZiQuAwardRate(), 100));
                    ziquAwardMoney = JYMathDoubleUtils.scaleHalfUp(ziquAwardMoney);
                    // 总的优惠金额
                    awardMoney = JYMathDoubleUtils.add(awardMoney, ziquAwardMoney);
                    shopAwardMoney = JYMathDoubleUtils.add(shopAwardMoney, ziquAwardMoney);
                    // 支付金额
                    mustPayMoney = JYMathDoubleUtils.sub(mustPayMoney, ziquAwardMoney);
                    orderInfo.setAwardMoney(awardMoney);
                    orderInfo.setShopAwardMoney(shopAwardMoney);
                    orderInfo.setPlatformAwardMoney(platformAwardMoney);
                    orderInfo.setTotalPrice(mustPayMoney);//待支付金额
                }
                orderInfo.setZiQuAwardMoney(ziquAwardMoney);
            }

            //餐具费用
            if (null != canJuCount && canJuCount > 0) { //用户选择参数
                //店铺是否提供餐具
                //hasCanJu;//是否提供餐具 0不提供，1提供按订单收费，2按餐具数量收费
                //canJuPrice;//餐具费用（1单或1套）
                if (null != shopInfo
                        && null != shopInfo.getHasCanJu() && shopInfo.getHasCanJu() > 0 //餐具收费
                        && null != shopInfo.getCanJuPrice() && shopInfo.getCanJuPrice() > 0//每套价格不为0
                ) {

                    Double canJuMoney = 0d;//餐具总金额
                    //店铺提供餐具且餐具收费
                    switch (shopInfo.getHasCanJu()) {
                        case SHOP_CAN_JU_TYPE.ORDER: {//1 按订单收费
                            //按订单收费的话不需要计算费用，直接使用就可以
                            canJuMoney = shopInfo.getCanJuPrice();
                        }
                        break;
                        case SHOP_CAN_JU_TYPE.COUNT: {//2 按餐具数量收费
                            //计算总的金额
                            canJuMoney = JYMathDoubleUtils.mul(canJuCount, shopInfo.getCanJuPrice());
                        }
                        break;
                    }

                    orderInfo.setCanJuCount(canJuCount);
                    orderInfo.setCanJuPrice(canJuMoney);
                    totalMoney = JYMathDoubleUtils.add(orderInfo.getTotalMoney(), canJuMoney);
                    mustPayMoney = JYMathDoubleUtils.add(orderInfo.getTotalPrice(), canJuMoney);
                    orderInfo.setTotalMoney(totalMoney);//订单总金额
                    orderInfo.setTotalPrice(mustPayMoney);//待支付金额
                } else {
                    //1. 无店铺
                    //2. 店铺不提供餐具
                    //3. 餐具不收费
                    orderInfo.setCanJuCount(0);
                    orderInfo.setCanJuPrice(0d);
                }
            } else { //不要餐具
                if (null != shopInfo
                        && null != shopInfo.getHasCanJu() && shopInfo.getHasCanJu() > 0 //餐具收费
                        && null != shopInfo.getCanJuPrice() && shopInfo.getCanJuPrice() > 0//每套价格不为0
                        && 0 == SHOP_CAN_JU_TYPE.ORDER_AWARD - shopInfo.getHasCanJu()//不选择餐具，按订单优惠对应的金额
                ) {
                    Double canJuMoney = shopInfo.getCanJuPrice();//餐具优惠总金额
                    orderInfo.setCanJuCount(0);
                    orderInfo.setCanJuPrice(-canJuMoney);
                    totalMoney = JYMathDoubleUtils.sub(orderInfo.getTotalMoney(), canJuMoney);
                    mustPayMoney = JYMathDoubleUtils.sub(orderInfo.getTotalPrice(), canJuMoney);
                    orderInfo.setTotalMoney(totalMoney);//订单总金额
                    orderInfo.setTotalPrice(mustPayMoney);//待支付金额
                } else {
                    orderInfo.setCanJuCount(0);
                    orderInfo.setCanJuPrice(0d);
                }
            }

        }
        // 减免配送费活动
        if (ValidateUtil.isAbsDouble(deliveryPrice) && SYS_SETTINGS.HAS_REDUCE_DELIVERY_PRICE_GAME == 1) {
            orderInfo = doOrderDeliveryPriceGame(shopInfo, gameId, gameRuleId, gameInfoJson, orderNo, orderInfo, time, orderInfo.getTotalMoney(), orderInfo.getTotalPrice(), submitUsername, deliveryPrice, orderSubmitResult);
            if (null == orderInfo) {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("活动解析错误，请稍后再试.");
                return orderSubmitResult;
            }
            awardMoney = orderInfo.getAwardMoney();
            mustPayMoney = orderInfo.getTotalPrice();
            platformAwardMoney = orderInfo.getPlatformAwardMoney();
            shopAwardMoney = orderInfo.getShopAwardMoney();
        }

        // todo : 计算税费 0 没有税费 1 商品总金额 + 打包费 + 配送费 - 优惠金额 * %
        if (SYS_SETTINGS.TAX_CALCULATION_TYPE == 1) {
            Integer rate = shopInfo.getShopTaxRate();
            if ((rate == null || rate <= 0) && (SYS_SETTINGS.PLATFORM_TAX_RATE != null && SYS_SETTINGS.PLATFORM_TAX_RATE > 0)) {
                rate = SYS_SETTINGS.PLATFORM_TAX_RATE;
            }
            if (rate != null && rate > 0) {
                // 税费 商品金额+ 打包费 减去优惠金额
                double total = orderInfo.getTotalPrice();
                if (ValidateUtil.isAbsDouble(orderInfo.getDeliveryPrice())) {
                    total = JYMathDoubleUtils.sub(total, orderInfo.getDeliveryPrice());
                }
                if (ValidateUtil.isAbsDouble(orderInfo.getZiQuAwardMoney())) {
                    total = JYMathDoubleUtils.add(total, orderInfo.getZiQuAwardMoney());
                }
                taxMoneyV1 = JYMathDoubleUtils.add(taxMoneyV1, JYMathDoubleUtils.mul(total, JYMathDoubleUtils.div(rate, 100)));
                // if (ValidateUtil.isAbsDouble(orderInfo.getDeliveryPrice())) {
                //     taxMoneyV1 = JYMathDoubleUtils.add(taxMoneyV1, JYMathDoubleUtils.mul(JYMathDoubleUtils.sub(orderInfo.getTotalPrice(), orderInfo.getDeliveryPrice()), JYMathDoubleUtils.div(rate, 100)));
                // } else {
                //     taxMoneyV1 = JYMathDoubleUtils.add(taxMoneyV1, JYMathDoubleUtils.mul(orderInfo.getTotalPrice(), JYMathDoubleUtils.div(rate, 100)));
                // }
                taxMoneyV1 = JYMathDoubleUtils.scaleHalfUp(taxMoneyV1);
            }
        } else if (SYS_SETTINGS.TAX_CALCULATION_TYPE == 0) {
            taxMoneyV1 = 0.0d;
        }
        // todo: 小费进入计算
        if ((null != tipMoney && tipMoney > 0) || (ValidateUtil.isAbsDouble(tipRate))) {
            if (ValidateUtil.isAbsDouble(tipRate)) {
                if (ValidateUtil.isAbsDouble(orderInfo.getDeliveryPrice())) {
                    tipMoney = JYMathDoubleUtils.mul(JYMathDoubleUtils.sub(orderInfo.getTotalPrice(), orderInfo.getDeliveryPrice()), JYMathDoubleUtils.div(tipRate, 100));
                } else {
                    tipMoney = JYMathDoubleUtils.mul(orderInfo.getTotalPrice(), JYMathDoubleUtils.div(tipRate, 100));
                }
                // tipMoney = JYMathDoubleUtils.mul(orderInfo.getTotalPrice(), JYMathDoubleUtils.div(tipRate, 100));
                tipMoney = JYMathDoubleUtils.scaleHalfUp(tipMoney);
            }
            orderInfo.setTipMoney(tipMoney);
            totalMoney = JYMathDoubleUtils.add(orderInfo.getTotalMoney(), tipMoney);
            mustPayMoney = JYMathDoubleUtils.add(orderInfo.getTotalPrice(), tipMoney);
            orderInfo.setTotalMoney(totalMoney);//订单总金额
            orderInfo.setTotalPrice(mustPayMoney);//待支付金额
        }
        // todo: 计入税费
        if (taxMoneyV1 > 0) {
            orderInfo.setGoodsTaxMoney(taxMoneyV1);
            totalMoney = JYMathDoubleUtils.add(orderInfo.getTotalMoney(), taxMoneyV1);
            mustPayMoney = JYMathDoubleUtils.add(orderInfo.getTotalPrice(), taxMoneyV1);
            orderInfo.setTotalMoney(totalMoney);    // 订单总金额
            orderInfo.setTotalPrice(mustPayMoney);  //  待支付金额
        }

        // vip 开通费用费用
        if (ValidateUtil.isID(vipPacketGameId) && vipPacketGame != null && SYS_SETTINGS.HAS_MEMBER_RECHARGE == 1) {
            totalMoney = JYMathDoubleUtils.add(orderInfo.getTotalMoney(), vipPacketGame.getVipOpenPrice());
            mustPayMoney = JYMathDoubleUtils.add(orderInfo.getTotalPrice(), vipPacketGame.getVipOpenPrice());
            orderInfo.setTotalMoney(totalMoney);    // 订单总金额
            orderInfo.setTotalPrice(mustPayMoney);  //  待支付金额
            orderInfo.setUseVipPacket(useVipPacket == null ? 0 : useVipPacket);
            orderInfo.setVipPacketGameId(vipPacketGameId);
        }
        // 新用户折扣开始计算
        if ((isFreeGood != null && isFreeGood == 1) || isDisCountOrder == 1 || ValidateUtil.isNotNull(exchangeCode)) {
            orderInfo = doDisCountOrderRate(orderInfo, isFreeGood, isDisCountOrder, exchangeCode, submitUsername);
            if (null == orderInfo) {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("新用户免单获取错误");
                return orderSubmitResult;
            }
            mustPayMoney = orderInfo.getTotalPrice();
            awardMoney = orderInfo.getAwardMoney();
        }
//        if (isDisCountOrder - 1 == 0) {
//
//
//        } else {
//            // 设置是不是免费的的订单
//            if (Optional.ofNullable(isFreeGood).orElse(0) == 1) {
//                orderInfo.setIsFreeGoodOrder(1);
//                orderInfo.setIsDiscountOrder(1);
//            }
//        }
        //支付单号
        orderInfo.setPayOrderNo(payOrderNo);
        Integer orderStatusInt = ORDER_STATUS.SUBMIT;
        // 线下支付
        if (isUnderLinePay != null && 0 == isUnderLinePay - 1) {
            orderInfo.setOrderStatus(ORDER_STATUS.UNDERLINE_SUBMIT);
            orderStatusInt = ORDER_STATUS.UNDERLINE_SUBMIT;
        }
        if (isIntegralOrder) {
            String city = "";
            try {
                city = URLEncoder.encode(ValidateUtil.isNull(buyCity) ? "" : buyCity, "utf-8");
                String params = "sysCustomer=" + SYS_CONFIG_PATH.FEN_XIAO_SERVICE_KEY + "&city="
                        + city +
                        "&orderNo=" + orderNo + "&username=" + orderInfo.getUsername() + "&integral=" + totalIntegral;
                String integralUrl = SYS_CONFIG_PATH.INTEGRAL_SERVICE_URL + "/api/distribute/integral/records/offset/pro";
                System.out.println("积分商城调用微服务参数：" + integralUrl + "\n" + params);
                String requestStr = HttpRequest.sendPost(integralUrl, params);
                if (null == requestStr) {
                    rollBackGoods(orderNo);
                    orderSubmitResult.setSuccess(false);
                    orderSubmitResult.setError("使用积分失败");
                    System.out.println("使用积分失败V3");
                    return orderSubmitResult;
                }
                System.out.println("积分商城调用微服务返回：" + requestStr);
                RecordsResult recordsResult = new Gson().fromJson(requestStr, RecordsResult.class);
                if (null == recordsResult) {
                    rollBackGoods(orderNo);
                    orderSubmitResult.setSuccess(false);
                    orderSubmitResult.setError("使用积分失败");
                    System.out.println("使用积分失败V2");
                    return orderSubmitResult;
                }
                if (0 == recordsResult.getStatus()) {
                    rollBackGoods(orderNo);
                    orderSubmitResult.setSuccess(false);
                    orderSubmitResult.setError(recordsResult.getError());
                    System.out.println(recordsResult.getError());
                    return orderSubmitResult;
                } else {
                    System.out.println("积分支付成功");
                    orderInfo.setIsPaid(1); // 已经消费掉了积分
                    // 积分商城订单，直接变为已支付，显示商家已接单，等待发货
                    orderInfo.setOrderStatus(ORDER_STATUS.SHOP_SURE);
                    orderStatusInt = ORDER_STATUS.SHOP_SURE;
                }
            } catch (Exception e) {
                e.printStackTrace();
                rollBackGoods(orderNo);
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("使用积分失败");
                return orderSubmitResult;
            }
        }
        orderInfo.setIsSpecifiedPostmen(0);
        // 是否启动收藏骑手优先抢单 蹄蹄
        if (likePostmanAdvance != null && likePostmanAdvance == 1 && orderInfo.getShopSelfPost() == 0 && orderInfo.getIsZiQu() == 0) {
            boolean isSpecifiedPostmen = isSpecifiedPostmen(orderInfo.getUsername(), orderInfo.getCity(), POSTMAN_TYPE.POSTMAN);
            if (isSpecifiedPostmen) {
                orderInfo.setIsSpecifiedPostmen(1);
            }
        }


        // 调度模式处理 2019年11月15日16:31:12 // 只有在调度优先的模式下 才会由调度到大厅内
        if (GrabOrderModeMan.getGrabOrderMode(orderInfo.getAgentId()) == GRAB_ORDER_MODE.DISPATCH_FIRST_TO_OTHER) {
            orderInfo.setDispatchState(ORDER_DISPATCH_STATE.ORDER_DISPATCH);
        }
//        // 设置是不是免费的的订单
//        if (Optional.ofNullable(isFreeGood).orElse(0) == 1) {
//            orderInfo.setIsFreeGoodOrder(1);
//        }
        // 调度模式处理结束
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.OrderInfo, orderInfo);
        } catch (SQLException e) {
            System.out.println("保存订单信息失败：" + e.getMessage());
            rollBackGoods(orderNo);
            e.printStackTrace();
            orderSubmitResult.setSuccess(false);
            orderSubmitResult.setError("存储订单信息失败，请稍后再试");
            return orderSubmitResult;
        }
        //4. 订单状态保存
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderNo(orderNo);
        orderStatus.setCreateUser(submitUsername);
//        orderStatus.setOrderStatus(ORDER_STATUS.SUBMIT);
        orderStatus.setCreateTime(DateUtils.getCurrTime());
        orderStatus.setOrderStatus(orderStatusInt);
        // end
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
        } catch (SQLException e) {
            rollBackGoods(orderNo);
            e.printStackTrace();
            orderSubmitResult.setSuccess(false);
            orderSubmitResult.setError("存储订单状态信息失败，请稍后再试");
            return orderSubmitResult;
        }

        //5 缓存
        //5.1 缓存订单信息
        OrderInfoMemory.getInstance().addOrderInfo(orderNo);
        //5.2 缓存订单商品信息
        OrderGoodsMemory.getInstance().addGoods(orderNo);
        //缓存订单店铺属性
        if (ValidateUtil.isNotNull(shopSpecs)) {
            OrderShopSpecsMemory.getInstance().addSpecs(orderNo);
        }

        //5.3 缓存订单状态信息
        OrderStatusMemory.getInstance().addStatus(orderNo);

        //检测是否在规定时间内支付
        OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null != info.getOrderType() && 0 != ORDER_TYPE.INTEGRAL_ORDER - info.getOrderType() && 0 != ORDER_TYPE.SHOP_GOODS_PRE - info.getOrderType() && 0 != ORDER_TYPE.SHOP_GOODS_STORE - info.getOrderType()) {
            OrderThread.map.put(orderNo, info);
        }

        //如果是分享商品购买
        if (null != orderType && 0 == orderType - ORDER_TYPE.SHARE_GOODS_ORDER) {
            //保存所关联的分享者信息
            //解析订单信息
            List<OrderGoodsVO> goodsVOList;
            try {
                goodsInfoJson = goodsInfoJson.replace("\\", "");
                goodsVOList = new Gson().fromJson(goodsInfoJson, new TypeToken<List<OrderGoodsVO>>() {
                }.getType());
            } catch (Exception e) {
                e.printStackTrace();
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("商品解析有误，请稍后再试");
                return orderSubmitResult;
            }

            if (ValidateUtil.isAbsList(goodsVOList) && null != goodsVOList.get(0)
                    && ValidateUtil.isID(goodsVOList.get(0).getGoodsId())) {
                saveShareOrderInfo(shareUsername, orderNo, goodsVOList.get(0).getGoodsId(), submitUsername);
            }
        }

        if ((isUnderLinePay != null && 0 == 1 - isUnderLinePay) || isIntegralOrder) {
            // 线下支付 // 积分订单
        } else {
            //发送一条订单通知
            Notice.publishNotice2Person(sysAppKey, submitUsername, JPushMessage.USER, NoticeType.order, "订单信息", "您的订单已提交，请尽快支付");
        }
        orderSubmitResult.setSuccess(true);
        orderSubmitResult.setOrderNo(orderNo);
        orderSubmitResult.setOrderTotalMoney(totalMoney);
        orderSubmitResult.setMustPayMoney(mustPayMoney);
        orderSubmitResult.setAwardMoney(awardMoney);
        // 进行回调
//        if (Optional.ofNullable(isFreeGood).orElse(0) == 1) {
//            OrderPay.orderPayOver(null, appFlag,
//                    null, UserType.USER, orderNo, null, payOrderNo, false);
//        }
        if (Optional.ofNullable(orderInfo.getIsFreeGoodOrder()).orElse(0) == 1) {
            OrderPay.orderPayOver(null, appFlag,
                    null, UserType.USER, orderNo, null, payOrderNo, false);
        }
        return orderSubmitResult;
    }

    // 计算订单的配送时长
    public static Integer calculateOrderPsTime(OrderOverTimeInfo inf, Double distance) {
        if (SYS_SETTINGS.DELIVERY_TIME_BY_DISTANCE == null || SYS_SETTINGS.DELIVERY_TIME_BY_DISTANCE != 1) {
            return inf.getOrderOverTime();
        } else {
            if (ValidateUtil.isAbsDouble(distance)
                    && (ValidateUtil.isAbsInteger(inf.getFixedOrderPsTime()) || ValidateUtil.isAbsInteger(inf.getOutOneKmTime()) || ValidateUtil.isAbsDouble(inf.getWithPsKmInRang()))) {
                double rang = ValidateUtil.isAbsDouble(inf.getWithPsKmInRang()) ? inf.getWithPsKmInRang() : 0.0;
                int out = rang >= distance ? 0 : (int) JYMathDoubleUtils.round(JYMathDoubleUtils.sub(distance, rang), 0);
                int fixedTime = ValidateUtil.isAbsInteger(inf.getFixedOrderPsTime()) ? inf.getFixedOrderPsTime() : 0;
                int preTime = ValidateUtil.isAbsInteger(inf.getOutOneKmTime()) ? inf.getOutOneKmTime() : 0;
                return fixedTime + out * preTime;
            } else {
                return inf.getOrderOverTime();
            }
        }
    }


    private static OrderInfo doDisCountOrderRate(OrderInfo orderInfo, Integer isFreeOrder, Integer isDisCountOrder, String exchangeCode, String username) {
        if (isFreeOrder == null) {
            isFreeOrder = 0;
        }
        orderInfo.setIsFreeGoodOrder(isFreeOrder);
        Double discountMoney = 0.0d;
        if (isFreeOrder == 1) {
            orderInfo.setIsDiscountOrder(1).setDisCountRate(0.0d);  // 免单即为0折
            // 计算费用
            Double totalPrice = orderInfo.getTotalPrice();
            Double plateAwardPrice = orderInfo.getPlatformAwardMoney();
            Double awardPrice = orderInfo.getAwardMoney();
            if (!ValidateUtil.isAbsDouble(awardPrice)) {
                awardPrice = 0.0d;
            }
            if (!ValidateUtil.isAbsDouble(plateAwardPrice)) {
                plateAwardPrice = 0.0d;
            }
            if (ValidateUtil.isAbsDouble(totalPrice)) {
                plateAwardPrice = JYMathDoubleUtils.scaleHalfUp(JYMathDoubleUtils.add(totalPrice, plateAwardPrice));
                awardPrice = JYMathDoubleUtils.scaleHalfUp(JYMathDoubleUtils.add(totalPrice, awardPrice));
                discountMoney = totalPrice;
                totalPrice = 0.0d;
            }
            orderInfo.setPlatformAwardMoney(plateAwardPrice).setTotalPrice(totalPrice).setAwardMoney(awardPrice).setDiscountMoney(discountMoney);
            return orderInfo;
        }
        // 兑换码
        if (!UserOrderMan.userHasDiscountOrder(username) && ValidateUtil.isNotNull(exchangeCode) && SYS_SETTINGS.IS_OPEN_DISCOUNT_EXCHANGE_CODE == 1) {
            // 查看兑换码是否有效
            DiscountExchangeCodeInfo exchangeCodeByCode = SpringContextHolder.getBean(DiscountExchangeCodeService.class).findDiscountExchangeCodeByCode(exchangeCode);
            if (exchangeCodeByCode == null) {
                System.out.println("无效的验证码信息~~~");
                // 验证码无效
                return orderInfo;
            }
            Long localTime = DateUtils.getCurrTime();
            if (exchangeCodeByCode.getIsUse() == 1 || (exchangeCodeByCode.getStartTime() == null || exchangeCodeByCode.getEndTime() == null)
                    || localTime < exchangeCodeByCode.getStartTime() || localTime > exchangeCodeByCode.getEndTime()) {
                System.out.println("验证码已失效~~~");
                return orderInfo;
            }
            // 查看折扣率
            if (exchangeCodeByCode.getDiscountRate() == null || exchangeCodeByCode.getDiscountRate() < 0 || exchangeCodeByCode.getDiscountRate() > 100) {
                System.out.println("验证码折扣率设置不正确~~~");
                return orderInfo;
            }
            orderInfo.setDiscountExchangeCode(exchangeCodeByCode.getExchangeCode());
            Double discountRate = 0.0d;
            if (exchangeCodeByCode.getDiscountRate() > 0) {
                discountRate = JYMathDoubleUtils.div(exchangeCodeByCode.getDiscountRate().doubleValue(), 100);
            }

            Double totalPrice = orderInfo.getTotalPrice();
            Double plateAwardPrice = orderInfo.getPlatformAwardMoney();
            Double awardPrice = orderInfo.getAwardMoney();
            if (!ValidateUtil.isAbsDouble(awardPrice)) {
                awardPrice = 0.0d;
            }
            if (!ValidateUtil.isAbsDouble(plateAwardPrice)) {
                plateAwardPrice = 0.0d;
            }
            if (!ValidateUtil.isAbsDouble(totalPrice)) {
                totalPrice = 0.0d;
            }
            // 折扣率
            discountMoney = 0.0d;
            if (discountRate == 0.0d) {
                discountMoney = totalPrice;
            } else {
                discountMoney = JYMathDoubleUtils.mul(JYMathDoubleUtils.sub(1, discountRate), totalPrice);
            }
            // 标记为已使用
            boolean useFlag = SpringContextHolder.getBean(DiscountExchangeCodeService.class).useDiscountExchangeCode(exchangeCode, orderInfo.getOrderNo(), discountMoney, exchangeCodeByCode.getVersion(), username);
            if (!useFlag) {
                System.out.println("使用失败~~~");
                return orderInfo;
            }
            plateAwardPrice = JYMathDoubleUtils.scaleHalfUp(JYMathDoubleUtils.add(plateAwardPrice, discountMoney));
            awardPrice = JYMathDoubleUtils.scaleHalfUp(JYMathDoubleUtils.add(awardPrice, discountMoney));
            totalPrice = JYMathDoubleUtils.scaleHalfUp(JYMathDoubleUtils.sub(totalPrice, discountMoney));
            if (!ValidateUtil.isAbsDouble(plateAwardPrice)) {
                plateAwardPrice = 0.0d;
            }
            if (!ValidateUtil.isAbsDouble(totalPrice)) {
                totalPrice = 0.0d;
            }
            orderInfo.setTotalPrice(totalPrice).setPlatformAwardMoney(plateAwardPrice).setDisCountRate(discountRate).setAwardMoney(awardPrice);
            orderInfo.setIsDiscountOrder(1).setDiscountMoney(discountMoney);
            if (discountRate == 0.0) {
                orderInfo.setIsFreeGoodOrder(1);
            }
            if (discountRate == 1.0) {
                orderInfo.setIsDiscountOrder(0);
            }
            orderInfo.setDiscountExchangeCode(exchangeCodeByCode.getExchangeCode());
            return orderInfo;
        }
        // 折扣
        if (!UserOrderMan.userHasOrder(username) && isDisCountOrder != null && isDisCountOrder == 1 && SYS_SETTINGS.NEW_USER_ORDER_DISCOUNT_RATE != null && SYS_SETTINGS.NEW_USER_ORDER_DISCOUNT_RATE >= 0 && SYS_SETTINGS.NEW_USER_ORDER_DISCOUNT_RATE <= 100) {
            Double disCountRate = JYMathDoubleUtils.scaleHalfUp(JYMathDoubleUtils.div(SYS_SETTINGS.NEW_USER_ORDER_DISCOUNT_RATE, 100));

            Double totalPrice = orderInfo.getTotalPrice();
            Double plateAwardPrice = orderInfo.getPlatformAwardMoney();
            Double awardPrice = orderInfo.getAwardMoney();
            if (!ValidateUtil.isAbsDouble(awardPrice)) {
                awardPrice = 0.0d;
            }
            if (!ValidateUtil.isAbsDouble(plateAwardPrice)) {
                plateAwardPrice = 0.0d;
            }
            if (!ValidateUtil.isAbsDouble(totalPrice)) {
                totalPrice = 0.0d;
            }
            // 折扣率
            discountMoney = 0.0d;
            if (disCountRate == 0) {
                discountMoney = totalPrice;
            } else {
                discountMoney = JYMathDoubleUtils.mul(JYMathDoubleUtils.sub(1, disCountRate), totalPrice);
            }
            plateAwardPrice = JYMathDoubleUtils.scaleHalfUp(JYMathDoubleUtils.add(plateAwardPrice, discountMoney));
            awardPrice = JYMathDoubleUtils.scaleHalfUp(JYMathDoubleUtils.add(awardPrice, discountMoney));
            totalPrice = JYMathDoubleUtils.scaleHalfUp(JYMathDoubleUtils.sub(totalPrice, discountMoney));
            if (!ValidateUtil.isAbsDouble(plateAwardPrice)) {
                plateAwardPrice = 0.0d;
            }
            if (!ValidateUtil.isAbsDouble(totalPrice)) {
                totalPrice = 0.0d;
            }
            orderInfo.setTotalPrice(totalPrice).setPlatformAwardMoney(plateAwardPrice).setDisCountRate(disCountRate).setAwardMoney(awardPrice);
            orderInfo.setIsDiscountOrder(1).setDiscountMoney(discountMoney);
            if (disCountRate == 0.0) {
                orderInfo.setIsFreeGoodOrder(1);
            }
            if (disCountRate == 1.0) {
                orderInfo.setIsDiscountOrder(0);
            }
            return orderInfo;
        }
        return orderInfo;
    }


    //保存分享商品购买订单关联信息
    private static void saveShareOrderInfo(String shareUsername, String orderNo, Long goodsId, String submitUsername) {
        ShareGoodOrderRelation shareGoodOrderRelation = new ShareGoodOrderRelation();
        shareGoodOrderRelation.setShareUsername(shareUsername);
        shareGoodOrderRelation.setUsername(submitUsername);
        shareGoodOrderRelation.setOrderNo(orderNo);
        shareGoodOrderRelation.setGoodsId(goodsId);
        shareGoodOrderRelation.setIsSuccess(0);
        shareGoodOrderRelation.setDelFlag(0);
        shareGoodOrderRelation.setCreateUser(submitUsername);
        shareGoodOrderRelation.setCreateTime(DateUtils.getCurrTime());

        try {
            DataDaoSql.getInstance().insertObj(PojoTables.SHARE_GOOD_ORDER_RELATION, shareGoodOrderRelation);
        } catch (SQLException e) {
            e.printStackTrace();
            return;
        }

    }

    //判断预约时间
    private static OrderSubmitResult checkAppointmentTime(Integer isAppointment, Long ziQuTime, ShopInfo shopInfo, OrderOverTimeInfo agentOrderOverTimeInfo) {
        // v1
        //       OrderSubmitResult result = new OrderSubmitResult();
        //
        //        if (null == isAppointment) {
        //            result.setSuccess(true);
        //            return result;
        //        }
        //
        //
        //        if (0 == isAppointment) {
        //            result.setSuccess(true);
        //            return result;
        //        }
        //
        //        if (null != isAppointment && 0 == 1 - isAppointment && (null == ziQuTime || ziQuTime < 1)) {
        //            result.setSuccess(false);
        //            result.setError("请先选择预约时间");
        //            return result;
        //        }
        //
        //        if (null == shopInfo) {
        //            result.setSuccess(false);
        //            result.setError("店铺不存在");
        //            return result;
        //        } else {
        //            //是否提供预约服务
        //            if (0 != 1 - shopInfo.getIsAppointment()) {
        //                result.setSuccess(false);
        //                result.setError("该店不提供预约服务!");
        //                return result;
        //            }
        //            //预约时间是否合适
        //            Integer afterDate = shopInfo.getAppointAfterDate();
        //            String time = shopInfo.getAppointAfterTime();
        //
        //            if (null == afterDate || null == time) {
        //                result.setSuccess(false);
        //                result.setError("该店不提供预约服务.");
        //                return result;
        //            }
        //            //超过店铺可预约时间
        //            if (afterDate > 0 && DateUtils.getAfterDaysTimestamp(afterDate) < ziQuTime) {
        //                result.setSuccess(false);
        //                result.setError("该店不提供预约服务.");
        //                return result;
        //            } else if (afterDate == 0) {
        //                //预约当天的。。。。。
        //            }
        //
        //            //todo 判断预约时间是否在可预约时段里
        //
        //            //获取预约时间的时间
        //
        //
        //        }
        //
        //        result.setSuccess(true);
        //        return result;

        // v2
        if (null == ziQuTime) {
            ziQuTime = 0l;
        }
        OrderSubmitResult result = new OrderSubmitResult();
        if (null != isAppointment && 0 == 1 - isAppointment && (null == ziQuTime || ziQuTime < 1)) {
            result.setSuccess(false);
            result.setError("请先选择预约时间");
            return result;
        }

        if (null == isAppointment) {
            // 没有预约，判断要求的时间是否为预约
            isAppointment = 0;
        }

        if (null == shopInfo) {
            result.setSuccess(false);
            result.setError("店铺不存在");
            return result;
        } else {
            if (null != agentOrderOverTimeInfo) {
                if (ValidateUtil.isAbsInteger(agentOrderOverTimeInfo.getIsAppointTime()) && agentOrderOverTimeInfo.getIsAppointTime() > 0) {
                    Integer apTime = agentOrderOverTimeInfo.getIsAppointTime();
                    if (ziQuTime > DateUtils.getCurrTime() + apTime * 60 * 1000) {
                        // 预约时间后，改订单直接是预约单
                        isAppointment = 1;
                        result.setIsAppointment(isAppointment);
                        result.setSuccess(true);
                        return result;
                    }
                } else {
                    // 直接非预约单
                    isAppointment = 0;
                    result.setIsAppointment(0);
                    result.setSuccess(true);
                    return result;
                }
            } else {
                if (0 == isAppointment) {
                    result.setIsAppointment(0);
                    result.setSuccess(true);
                    return result;
                }
                // 没有设置过按之前逻辑
                // 是否提供预约服务
                if (0 != 1 - shopInfo.getIsAppointment()) {
                    result.setSuccess(false);
                    result.setError("该店不提供预约服务!");
                    return result;
                }
                // 预约时间是否合适
                Integer afterDate = shopInfo.getAppointAfterDate();
                String time = shopInfo.getAppointAfterTime();

                if (null == afterDate || null == time) {
                    result.setSuccess(false);
                    result.setError("该店不提供预约服务.");
                    return result;
                }
                // 超过店铺可预约时间
                if (afterDate > 0 && DateUtils.getAfterDaysTimestamp(afterDate) < ziQuTime) {
                    result.setSuccess(false);
                    result.setError("该店不提供预约服务.");
                    return result;
                } else if (afterDate == 0) {
                    //预约当天的。。。。。
                }
            }
        }
        result.setIsAppointment(isAppointment);
        result.setSuccess(true);
        return result;

    }

    // 是否指定为收藏的配送员 true 标识 收藏者优先  false 一样
    public static boolean isSpecifiedPostmen(String username, String city, Integer postmanType) {
        if (SYS_SETTINGS.POSTMAN_LIKE_IS_FIRST == null
                || SYS_SETTINGS.POSTMAN_LIKE_IS_FIRST == 0
                || SYS_SETTINGS.LIKE_POSTMAN_UNROB_TIME == null
                || SYS_SETTINGS.LIKE_POSTMAN_UNROB_TIME <= 0
                || ValidateUtil.isNull(username)
                || ValidateUtil.isNull(city)) {
            return false;
        }
        List<PostManLike> list = PostManLikeMemory.getInstance().listOfPostManLikeByUsername(username);
        if (ValidateUtil.isAbsList(list)) {
            for (PostManLike p : list) {
                if (p == null) {
                    continue;
                }
                CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(p.getPostman());
                if (cityPostman == null) {
                    continue;
                }
                if (city.equals(cityPostman.getCity()) && cityPostman.getIsWork() == 1) {
                    // 有一个就行
                    if (postmanType != null) {
                        if (cityPostman.getType() != null && cityPostman.getType() == postmanType) {
                            return true;
                        } else {
                            return false;
                        }
                    } else {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    //订单提交处理-多店铺同时提交
    public static OrderSubmitResult submitMulitOrder(String sysAppKey, String appFlag,
                                                     String submitUsername,
                                                     Integer orderType,
                                                     Long deliveryId, Integer isUrgent,
                                                     String goodsInfoJson,
                                                     Integer isZiQu, Integer isAppointment, Long ziQuTime,
                                                     String buyName, String buyPhone,
                                                     Double buyLat, Double buyLng,
                                                     String buyProvince, String buyCity, String buyCounty, String buyAddress, String buyAddress2, String buyAddress3) {
        OrderSubmitResult orderSubmitResult = new OrderSubmitResult();

        //解析订单信息
        List<OrderInfoDB> orderDBList;
        try {
            goodsInfoJson = goodsInfoJson.replace("\\", "");
            orderDBList = new Gson().fromJson(goodsInfoJson, new TypeToken<List<OrderInfoDB>>() {
            }.getType());
        } catch (Exception e) {
            e.printStackTrace();
            orderSubmitResult.setSuccess(false);
//            orderSubmitResult.setError("商品解析有误，请稍后再试");
            orderSubmitResult.setError(PROMPTS.PARSING_IS_WRONG);
            return orderSubmitResult;
        }

        String payOrderNo = "M" + OrderUtils.getOrderNo();
        Double orderTotalMoney = 0d;//订单总金额
        Double mustPayMoney = 0d;//订单待支付金额
        Double awardMoney = 0d;//订单满减金额
        Double platformAwardMoney = 0d;//订单平台满减金额
        Double shopAwardMoney = 0d;//订单店铺满减金额

        if (ValidateUtil.isAbsList(orderDBList)) {
            for (int i = 0; i < orderDBList.size(); i++) {
                OrderInfoDB orderInfoDB = orderDBList.get(i);
                if (null == orderInfoDB) {
                    continue;
                }

                //支付订单编号
                OrderSubmitResult result = submitOrder(sysAppKey, appFlag,
                        submitUsername, orderInfoDB.getShopId(),
                        orderType,
                        payOrderNo,
                        deliveryId,
                        0d, 0d, 0,
                        isUrgent,
                        new Gson().toJson(orderInfoDB.getGoods()),
                        isZiQu, isAppointment, ziQuTime,
                        null,
                        buyName, buyPhone,
                        buyLat, buyLng, buyProvince, buyCity, buyCounty, buyAddress, buyAddress2, buyAddress3,
                        orderInfoDB.getNote(),
                        null, null,
                        new Gson().toJson(orderInfoDB.getGameInfo()), new Gson().toJson(orderInfoDB.getRedpacketInfo()),
                        null, // 小费
                        null,// 税费
                        null,
                        null,
                        null // 收藏骑手优先抢单
                ); // 是否线下支付

                if (null == result) {
                    orderSubmitResult.setSuccess(false);
//                    orderSubmitResult.setError("提交订单失败，请稍后再试");
                    orderSubmitResult.setError(PROMPTS.SUBMIT_ORDER_FAILED);
                    return orderSubmitResult;
                } else {
                    if (!result.isSuccess()) {
                        return result;
                    }
                }
                orderTotalMoney = JYMathDoubleUtils.add(orderTotalMoney, result.getOrderTotalMoney());
                mustPayMoney = JYMathDoubleUtils.add(mustPayMoney, result.getMustPayMoney());
                awardMoney = JYMathDoubleUtils.add(awardMoney, result.getAwardMoney());
                platformAwardMoney = JYMathDoubleUtils.add(platformAwardMoney, result.getPlatformAwardMoney());
                shopAwardMoney = JYMathDoubleUtils.add(shopAwardMoney, result.getShopAwardMoney());
            }
        }

        orderSubmitResult.setSuccess(true);
        orderSubmitResult.setOrderTotalMoney(orderTotalMoney);
        orderSubmitResult.setMustPayMoney(mustPayMoney);
        orderSubmitResult.setAwardMoney(awardMoney);
        orderSubmitResult.setPlatformAwardMoney(platformAwardMoney);
        orderSubmitResult.setShopAwardMoney(shopAwardMoney);
        orderSubmitResult.setOrderNo(payOrderNo);
        return orderSubmitResult;
    }




    //保存活动信息
    private static OrderSubmitResult saveDeliveryPriceGameInfo(Long gameId, Long gameRuleId,
                                                               String orderNo, OrderInfo orderInfo, Long time,
                                                               Double orderTotalMoney,
                                                               Double awardMoney, Double platformAwardMoney, Double shopAwardMoney,
                                                               Double mustPayMoney,
                                                               String submitUsername, String shopName, Double deliveryPrice) {
        OrderSubmitResult orderSubmitResult = new OrderSubmitResult();
        if (deliveryPrice == null || deliveryPrice <= 0) {
            orderSubmitResult.setSuccess(true);
            orderSubmitResult.setMustPayMoney(mustPayMoney);
            orderSubmitResult.setAwardMoney(awardMoney);
            orderSubmitResult.setPlatformAwardMoney(platformAwardMoney);
            orderSubmitResult.setShopAwardMoney(shopAwardMoney);
            return orderSubmitResult;
        }



        orderSubmitResult.setSuccess(true);
        orderSubmitResult.setOrderNo(orderNo);
        orderSubmitResult.setMustPayMoney(mustPayMoney);
        orderSubmitResult.setAwardMoney(awardMoney);
        orderSubmitResult.setPlatformAwardMoney(platformAwardMoney);
        orderSubmitResult.setShopAwardMoney(shopAwardMoney);
        return orderSubmitResult;
    }



    //--------------------订单回滚
    public static boolean rollBackGoods(String orderNo) {

        return true;
    }

    private static boolean rollbackMOrder(List<OrderInfo> orderInfoList, String orderNo) {
        StringBuffer sql = new StringBuffer();
        sql.append(" update ").append(PojoTables.OrderInfo).append(" set delFlag = 1 where delFlag = 0 and orderNo in ");

        HashSet<String> set = new HashSet<>();
        if (ValidateUtil.isAbsList(orderInfoList)) {
            for (OrderInfo orderInfo : orderInfoList) {
                if (orderInfo != null && ValidateUtil.isNotNull(orderInfo.getOrderNo())) {
                    set.add(orderInfo.getOrderNo());
                }
            }
        }
        if (ValidateUtil.isNotNull(orderNo)) {
            set.add(orderNo);
        }
        sql.append("(").append(StringUtils.join(set, ",")).append(")");
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }


        // 清空缓存
        return true;
    }

    // 重量参与配送费计算
    private static OrderSubmitResult doOrderWeightDeliveryPrice(Integer isZiQu, Double totalWeight, Double deliveryPrice, ShopInfo shopInfo, Long cityAgentId,
                                                                OrderSubmitResult orderSubmitResult) {
        if (null != isZiQu && 0 == isZiQu && totalWeight != null) {
            if (shopInfo != null) {
                if (deliveryPrice == null) {
                    deliveryPrice = 0.0d;
                }
                Double fixedWeightCost = shopInfo.getFixedWeightCost();
                Double withinWeight = shopInfo.getWithinWeight();
                Double oneKgWeightCost = shopInfo.getOneKgWeightCost();
                if (ValidateUtil.isNotAbsDouble(fixedWeightCost)
                        && ValidateUtil.isNotAbsDouble(withinWeight)
                        && ValidateUtil.isNotAbsDouble(oneKgWeightCost)
                ) {
                    // 商圈的
                    if (ValidateUtil.isID(cityAgentId)) {
                        CityAgent cityAgent = CityAgentMemory.getInstance().getById(cityAgentId);
                        if (cityAgent != null) {
                            fixedWeightCost = cityAgent.getFixedWeightCost();
                            withinWeight = cityAgent.getWithinWeight();
                            oneKgWeightCost = cityAgent.getOneKgWeightCost();
                        }
                    }
                }

                // 若没有 就不在计算了
                if (ValidateUtil.isNotAbsDouble(fixedWeightCost)
                        && ValidateUtil.isNotAbsDouble(withinWeight)
                        && ValidateUtil.isNotAbsDouble(oneKgWeightCost)
                ) {
                } else {
                    if (JYMathDoubleUtils.sub(totalWeight, withinWeight) <= 0) {
                        deliveryPrice = JYMathDoubleUtils.add(deliveryPrice, fixedWeightCost);
                    } else {
                        Double after = JYMathDoubleUtils.sub(totalWeight, withinWeight);
                        deliveryPrice = JYMathDoubleUtils.add(deliveryPrice, JYMathDoubleUtils.add(fixedWeightCost, JYMathDoubleUtils.mul(after, oneKgWeightCost)));
                    }
                    orderSubmitResult.setOrderDeliveryPrice(deliveryPrice);
                }
            }
        }
        return orderSubmitResult;
    }


    //配送费处理
    private static OrderSubmitResult doDeliveryPrice(Integer isZiQu, ShopInfo shopInfo,
                                                     UserAddress userAddress, Long agentId,
                                                     CityAgent cityAgent, Double deliveryPrice,
                                                     Double buyLat, Double buyLng,
                                                     Double ridingDistance,
                                                     OrderSubmitResult orderSubmitResult) {
        if (null != isZiQu && 0 == isZiQu) {//需要配送
            if (ValidateUtil.isNotLatLng(shopInfo.getLat(), shopInfo.getLng())) {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("店铺位置信息不准确，请联系客服");
                return orderSubmitResult;
            }

            //验证配送范围
            if (null != SYS_SETTINGS.SHOP_MANAGE_TYPE && 0 == SHOP_MANAGE_TYPE_FREE_OR_AGENT.AGENT - SYS_SETTINGS.SHOP_MANAGE_TYPE) {
                //如果是按学校这种精确配送员的  需要验证店铺对应的收货地址是在同一个范围内吗
                if (null != userAddress) { //收货地址方式
                    if (ValidateUtil.isAbsLong(userAddress.getAgentId())) {//地址里有代理
                        if (0 != userAddress.getAgentId() - agentId) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服");
                            return orderSubmitResult;
                        }
                    } else {//地址里没有代理  验证用户的收货地址，是否在店铺所在代理的配送范围
                        if (null != SYS_SETTINGS.USER_ADDRESS_IS_AGENT && 0 != 1 - SYS_SETTINGS.USER_ADDRESS_IS_AGENT) {
                            Integer postRange = cityAgent.getRang();
                            if (ValidateUtil.isNotAbsInteger(postRange)) {
                                postRange = 0;
                            }
                            if (ValidateUtil.isNotLatLng(cityAgent.getLat(), cityAgent.getLng())) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("店铺所在商圈未设置经纬度，请联系客服");
                                return orderSubmitResult;
                            }

                            //验证收货距离
                            double distinct = Geohash.distance(cityAgent.getLat(), cityAgent.getLng(), userAddress.getLat(), userAddress.getLng());
                            if (JYMathDoubleUtils.sub(distinct, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出商圈的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }

                            //验证收货地址距离店铺是否超出距离
                            if (null != shopInfo) {
                                double distinctShop = Geohash.distance(shopInfo.getLat(), shopInfo.getLng(), userAddress.getLat(), userAddress.getLng());
                                if (JYMathDoubleUtils.sub(distinctShop, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                    return orderSubmitResult;
                                }
                            }

                        }
                    }

                    //配送费计算方式
                    if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 2 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) { //配送费计算方式 1固定配送费 2 按距离（平台）计算 3按距离（店铺）
                        //2 按距离（平台）计算
                        if (ValidateUtil.isNotLatLng(userAddress.getLat(), userAddress.getLng())) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                            return orderSubmitResult;
                        }
                        //验证按距离计算的配送费是否正确
                        Double distance = 0.0d;
                        // 实际骑行的距离
                        if (SYS_SETTINGS.IS_RIDING_DISTANCE == 1) {
                            distance = ValidateUtil.isAbsDouble(ridingDistance) ? ridingDistance : 0.0d;
                        } else {
                            distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
                        }
                        // Double distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
                        SysVariablePaotui sysVariablePaotui = SysVariablePaotuiMemory.getInstance().getByCode(7);
                        Double km = JYMathDoubleUtils.div(distance, 1000);

                        if (null != cityAgent) {
                            Integer postRange = cityAgent.getRang();
                            if (JYMathDoubleUtils.sub(km, postRange) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                        }

                        if (sysVariablePaotui != null) {
                            // 如果设置比列  则按照比例计算距离
                            if (SYS_SETTINGS.IS_RIDING_DISTANCE != 1) {
                                if (SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
                                    Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
                                    distance = JYMathDoubleUtils.mul(distance, rate);
                                }
                            }
                            orderSubmitResult.setDistance(distance);
                            km = JYMathDoubleUtils.div(distance, 1000);
                            if (km - Double.parseDouble(sysVariablePaotui.getRang()) <= 0) {
                                String money = sysVariablePaotui.getVal();
                                if (ValidateUtil.isNotNull(money)) {
                                    deliveryPrice = Double.parseDouble(money);
                                }
                            } else {
//                                Double after = km - Double.parseDouble(sysVariablePaotui.getRang());
                                Double after = JYMathDoubleUtils.sub(km, Double.parseDouble(sysVariablePaotui.getRang()));
                                Double round = Math.ceil(after);
//                                String money = String.valueOf(Double.parseDouble(sysVariablePaotui.getVal()) + (round * Double.parseDouble(sysVariablePaotui.getPre())));
//                                if (ValidateUtil.isNotNull(money)) {
//                                    deliveryPrice = Double.parseDouble(money);
//                                }
                                deliveryPrice = JYMathDoubleUtils.add(Double.parseDouble(sysVariablePaotui.getVal()), JYMathDoubleUtils.mul(round, Double.parseDouble(sysVariablePaotui.getPre())));
                            }
                        } else {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("查不到配置参数");
                            return orderSubmitResult;
                        }
                    } else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 3 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
                        // 3按距离（店铺）
                        if (ValidateUtil.isNotLatLng(userAddress.getLat(), userAddress.getLng())) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                            return orderSubmitResult;
                        }

                        //验证按距离(店铺)计算的配送费是否正确
                        // Double distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
                        Double distance = 0.0D;
                        if (SYS_SETTINGS.IS_RIDING_DISTANCE == 1) {
                            distance = ValidateUtil.isAbsDouble(ridingDistance) ? ridingDistance : 0.0d;
                        } else {
                            distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
                        }
                        orderSubmitResult.setDistance(distance);
                        Double km = JYMathDoubleUtils.div(distance, 1000);//距离
                        if (null != cityAgent) {
                            Integer postRange = cityAgent.getRang();
                            if (JYMathDoubleUtils.sub(km, postRange) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                        }

                        //价格计算方式：基础配送费+上取整（实际下单距离-基础范围）*超出后每公里的价格

                        //v2 店铺没有这只规则的时候，使用平台的规则
                        //withinDistance 范围
                        Double withinDistance = shopInfo.getWithinDistance();
                        //fixedCost 范围内价格
                        Double fixedCost = shopInfo.getFixedCost();
                        //oneKmCost 超出后每公里价格
                        Double oneKmCost = shopInfo.getOneKmCost();
                        if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                            //店铺未设置规则
                            //查看商圈的公式值
                            if (null == cityAgent) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("配送费规则设置的不正确，请联系客服");
                                return orderSubmitResult;
                            }
                            // 指定是时间段的
                            CityAgentFeeMan.assignmentCityAgentFeeByTime(cityAgent, DateUtils.getCurrTime());
                            //withinDistance 范围
                            withinDistance = cityAgent.getWithinDistance();
                            //fixedCost 范围内价格
                            fixedCost = cityAgent.getFixedCost();
                            //oneKmCost 超出后每公里价格
                            oneKmCost = cityAgent.getOneKmCost();
                        }
                        if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                            //不收配送费
                        } else {
                            // 如果设置比列  则按照比例计算距离
                            if (SYS_SETTINGS.IS_RIDING_DISTANCE != 1 && SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
                                Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
                                distance = JYMathDoubleUtils.mul(distance, rate);
                            }
                            km = JYMathDoubleUtils.div(distance, 1000);
                            if (km - withinDistance <= 0) {
                                deliveryPrice = fixedCost;
                            } else {
//                                Double after = km - withinDistance;
                                Double after = JYMathDoubleUtils.sub(km, withinDistance);
                                Double round = Math.ceil(after);
//                                deliveryPrice = fixedCost + round * oneKmCost;
                                deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
                            }
                        }

//                        //v1 只按店铺的规则
//                        if (shopInfo.getFixedCost() != null && shopInfo.getOneKmCost() != null && shopInfo.getWithinDistance() != null) {
//                            if (km - shopInfo.getWithinDistance() <= 0) {
//                                deliveryPrice = shopInfo.getFixedCost();
//                            } else {
//                                Double after = km - shopInfo.getWithinDistance();
//                                Double round = Math.ceil(after);
//                                deliveryPrice = shopInfo.getFixedCost() + round * shopInfo.getOneKmCost();
//                            }
//                        } else {
//                            orderSubmitResult.setSuccess(false);
//                            orderSubmitResult.setError("查不到配置参数");
//                            return orderSubmitResult;
//                        }


                    }
//                    else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 4 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
//                        // 4按商圈设置的时间段进行判断
//                        // 验证按距离(店铺)计算的配送费是否正确
//                        Double distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
//                        // 如果设置比列  则按照比例计算距离
//                        if (SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
//                            Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
//                            distance = JYMathDoubleUtils.mul(distance, rate);
//                        }
//                        Double km = JYMathDoubleUtils.div(distance, 1000);//距离
//                        //价格计算方式：基础配送费+上取整（实际下单距离-基础范围）*超出后每公里的价格
//
//                        CityAgentFeeInfo info = CityAgentFeeMan.getCityAgentFeeByTime(cityAgent.getId(), DateUtils.getCurrTime());
//                        if (info == null) {
//                            orderSubmitResult.setSuccess(false);
//                            orderSubmitResult.setError("当前商圈尚未设置费用,请重新选择地址或联系客服。");
//                            return orderSubmitResult;
//                        }
//                        //withinDistance 范围
//                        Double withinDistance = info.getWithinDistance();
//                        //fixedCost 范围内价格
//                        Double fixedCost = info.getFixedCost();
//                        //oneKmCost 超出后每公里价格
//                        Double oneKmCost = info.getOneKmCost();
//                        if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
//                            //不收配送费
//                        } else {
//                            if (km - withinDistance <= 0) {
//                                deliveryPrice = fixedCost;
//                            } else {
//                                Double after = JYMathDoubleUtils.sub(km, withinDistance);
//                                Double round = Math.ceil(after);
//                                deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
//                            }
//                        }
//                    }
                } else { //传入经纬度方式
                    if (null != SYS_SETTINGS.USER_ADDRESS_IS_AGENT && 0 != 1 - SYS_SETTINGS.USER_ADDRESS_IS_AGENT) {
                        Integer postRange = cityAgent.getRang();
                        if (ValidateUtil.isNotAbsInteger(postRange)) {
                            postRange = 0;
                        }
                        if (ValidateUtil.isNotLatLng(cityAgent.getLat(), cityAgent.getLng())) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("店铺所在商圈未设置经纬度，请联系客服");
                            return orderSubmitResult;
                        }

                        //验证收货距离
                        double distinct = Geohash.distance(cityAgent.getLat(), cityAgent.getLng(), buyLat, buyLng);
                        if (JYMathDoubleUtils.sub(distinct, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                            return orderSubmitResult;
                        }

                        if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 2 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) { //配送费计算方式 1固定配送费
                            // 2按距离计算(平台)
                            if (ValidateUtil.isNotLatLng(buyLat, buyLng)) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                                return orderSubmitResult;
                            }

                            //验证按距离计算的配送费是否正确
                            Double distance = 0.0d;
                            if (SYS_SETTINGS.IS_RIDING_DISTANCE == 1) {
                                distance = ValidateUtil.isAbsDouble(ridingDistance) ? ridingDistance : 0.0d;
                            } else {
                                distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                            }
                            // Double distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                            SysVariablePaotui sysVariablePaotui = SysVariablePaotuiMemory.getInstance().getByCode(7);
                            Double km = JYMathDoubleUtils.div(distance, 1000);
                            //验证收货地址距离店铺是否超出距离
                            if (JYMathDoubleUtils.sub(km, postRange) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }

                            if (sysVariablePaotui != null) {
                                // 如果设置比列  则按照比例计算距离的费用
                                if (SYS_SETTINGS.IS_RIDING_DISTANCE != 1 && SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
                                    Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
                                    distance = JYMathDoubleUtils.mul(distance, rate);
                                }
                                orderSubmitResult.setDistance(distance);
                                km = JYMathDoubleUtils.div(distance, 1000);
                                if (km - Double.parseDouble(sysVariablePaotui.getRang()) <= 0) {
                                    String money = sysVariablePaotui.getVal();
                                    if (ValidateUtil.isNotNull(money)) {
                                        deliveryPrice = Double.parseDouble(money);
                                    }
                                } else {
                                    Double after = JYMathDoubleUtils.sub(km, Double.parseDouble(sysVariablePaotui.getRang()));
                                    Double round = Math.ceil(after);
                                    deliveryPrice = JYMathDoubleUtils.add(Double.parseDouble(sysVariablePaotui.getVal()), JYMathDoubleUtils.mul(round, Double.parseDouble(sysVariablePaotui.getPre())));
                                }
                            } else {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("查不到配置参数");
                                return orderSubmitResult;
                            }
                        } else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 3 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
                            // 3按距离（店铺）
                            if (ValidateUtil.isNotLatLng(buyLat, buyLng)) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                                return orderSubmitResult;
                            }

                            //验证按距离(店铺)计算的配送费是否正确
                            // Double distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                            Double distance = 0.0D;
                            if (SYS_SETTINGS.IS_RIDING_DISTANCE == 1) {
                                distance = ValidateUtil.isAbsDouble(ridingDistance) ? ridingDistance : 0.0d;
                            } else {
                                distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                            }
                            Double km = JYMathDoubleUtils.div(distance, 1000);
                            //验证收货地址距离店铺是否超出距离
                            if (JYMathDoubleUtils.sub(km, postRange) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }


                            //v2 店铺没有这只规则的时候，使用平台的规则
                            //withinDistance 范围
                            Double withinDistance = shopInfo.getWithinDistance();
                            //fixedCost 范围内价格
                            Double fixedCost = shopInfo.getFixedCost();
                            //oneKmCost 超出后每公里价格
                            Double oneKmCost = shopInfo.getOneKmCost();
                            if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                                //店铺未设置规则
                                //查看商圈的公式值
                                if (null == cityAgent) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("配送费规则设置的不正确，请联系客服");
                                    return orderSubmitResult;
                                }
                                // 指定是时间段的
                                CityAgentFeeMan.assignmentCityAgentFeeByTime(cityAgent, DateUtils.getCurrTime());
                                //withinDistance 范围
                                withinDistance = cityAgent.getWithinDistance();
                                //fixedCost 范围内价格
                                fixedCost = cityAgent.getFixedCost();
                                //oneKmCost 超出后每公里价格
                                oneKmCost = cityAgent.getOneKmCost();
                            }
                            if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                                //不收配送费
                            } else {
                                if (SYS_SETTINGS.IS_RIDING_DISTANCE != 1 && SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
                                    Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
                                    distance = JYMathDoubleUtils.mul(distance, rate);
                                }
                                km = JYMathDoubleUtils.div(distance, 1000);
                                if (km - withinDistance <= 0) {
                                    deliveryPrice = fixedCost;
                                } else {
                                    Double after = km - withinDistance;
                                    Double round = Math.ceil(after);
//                                    deliveryPrice = fixedCost + round * oneKmCost;
                                    deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
                                }
                            }
                            orderSubmitResult.setDistance(distance);

//                        //v1 只按店铺的规则
//                            if (shopInfo.getFixedCost() != null && shopInfo.getOneKmCost() != null && shopInfo.getWithinDistance() != null) {
//
//                                if (km - shopInfo.getWithinDistance() <= 0) {
//                                    deliveryPrice = shopInfo.getFixedCost();
//                                } else {
//                                    Double after = km - shopInfo.getWithinDistance();
//                                    Double round = Math.ceil(after);
//                                    deliveryPrice = shopInfo.getFixedCost() + round * shopInfo.getOneKmCost();
//                                }
//                            } else {
//                                orderSubmitResult.setSuccess(false);
//                                orderSubmitResult.setError("查不到配置参数");
//                                return orderSubmitResult;
//                            }
                        }
//                        else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 4 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
//                            // 4按商圈设置的时间段进行判断
//                            // 验证按距离(店铺)计算的配送费是否正确
//                            Double distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
//                            // 如果设置比列  则按照比例计算距离
//                            if (SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
//                                Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
//                                distance = JYMathDoubleUtils.mul(distance, rate);
//                            }
//                            Double km = JYMathDoubleUtils.div(distance, 1000);//距离
//                            //价格计算方式：基础配送费+上取整（实际下单距离-基础范围）*超出后每公里的价格
//
//                            CityAgentFeeInfo info = CityAgentFeeMan.getCityAgentFeeByTime(cityAgent.getId(), DateUtils.getCurrTime());
//                            if (info == null) {
//                                orderSubmitResult.setSuccess(false);
//                                orderSubmitResult.setError("当前商圈尚未设置费用,请重新选择地址或联系客服。");
//                                return orderSubmitResult;
//                            }
//                            //withinDistance 范围
//                            Double withinDistance = info.getWithinDistance();
//                            //fixedCost 范围内价格
//                            Double fixedCost = info.getFixedCost();
//                            //oneKmCost 超出后每公里价格
//                            Double oneKmCost = info.getOneKmCost();
//                            if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
//                                //不收配送费
//                            } else {
//                                if (km - withinDistance <= 0) {
//                                    deliveryPrice = fixedCost;
//                                } else {
//                                    Double after = JYMathDoubleUtils.sub(km, withinDistance);
//                                    Double round = Math.ceil(after);
//                                    deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
//                                }
//                            }
//                        }
                    }
                }
            }
        }
        if (cityAgent != null) {
            orderSubmitResult.setAgentId(cityAgent.getId());
        }
        orderSubmitResult.setOrderDeliveryPrice(deliveryPrice);
        return orderSubmitResult;
    }

    //配送费处理(新增围栏模式)
    private static OrderSubmitResult doDeliveryPriceV2(Integer isZiQu, ShopInfo shopInfo,
                                                       UserAddress userAddress, Long agentId,
                                                       CityAgent cityAgent, Double deliveryPrice,
                                                       Double buyLat, Double buyLng,
                                                       Double ridingDistance,
                                                       OrderSubmitResult orderSubmitResult) {
        if (null != isZiQu && 0 == isZiQu) {//需要配送
            if (ValidateUtil.isNotLatLng(shopInfo.getLat(), shopInfo.getLng())) {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("店铺位置信息不准确，请联系客服");
                return orderSubmitResult;
            }

            //验证配送范围
            if (null != SYS_SETTINGS.SHOP_MANAGE_TYPE && 0 == SHOP_MANAGE_TYPE_FREE_OR_AGENT.AGENT - SYS_SETTINGS.SHOP_MANAGE_TYPE) {
                //如果是按学校这种精确配送员的  需要验证店铺对应的收货地址是在同一个范围内吗
                if (null != userAddress) { //收货地址方式
                    if (ValidateUtil.isAbsLong(userAddress.getAgentId())) {//地址里有代理
                        if (0 != userAddress.getAgentId() - agentId) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服");
                            return orderSubmitResult;
                        }
                    } else { //地址里没有代理  验证用户的收货地址，是否在店铺所在代理的配送范围
                        if (null != SYS_SETTINGS.USER_ADDRESS_IS_AGENT && 0 != 1 - SYS_SETTINGS.USER_ADDRESS_IS_AGENT) {
                            Integer postRange = 0;
                            if (null != cityAgent) {
                                postRange = cityAgent.getRang();
                                if (ValidateUtil.isNotAbsInteger(postRange)) {
                                    postRange = 0;
                                }
                            }
//                            Integer postRange = cityAgent.getRang();
//                            if (ValidateUtil.isNotAbsInteger(postRange)) {
//                                postRange = 0;
//                            }

                            //验证收货距离
                            if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && 0 == 1 - SYS_SETTINGS.IS_ELECTRONIC_FENCE) {    // 是否启用电子围栏 0.不使用电子围栏 1.使用电子围栏
                                // 判断该用户是否在商圈内(多边形)
                                if (StringUtils.isEmpty(cityAgent.getLnglats())) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("商圈经纬度无效，请联系客服");
                                    return orderSubmitResult;
                                }
                                String[] latlngs = cityAgent.getLnglats().split(";");
                                Double[] lngArr = new Double[latlngs.length];
                                Double[] latArr = new Double[latlngs.length];
                                for (int j = 0; j < latlngs.length; j++) {
                                    String[] lnla = latlngs[j].split(",");
                                    lngArr[j] = Double.parseDouble(lnla[0]);
                                    latArr[j] = Double.parseDouble(lnla[1]);
                                }
                                Boolean flag = Geohash.isInPolygon(userAddress.getLng(), userAddress.getLat(), lngArr, latArr);
                                if (!flag) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服 ");
                                    return orderSubmitResult;
                                }
                                //验证收货地址距离店铺是否超出距离
                                if (null != shopInfo) {
//                                    if (SYS_SETTINGS.DELIVERY_DISTANCE_IS_NOT_CHECK != null && SYS_SETTINGS.DELIVERY_DISTANCE_IS_NOT_CHECK == 1) {
//                                        // 地址不验证收货地址
//                                    } else {
//                                        double distinctShop = Geohash.distance(shopInfo.getLat(), shopInfo.getLng(), userAddress.getLat(), userAddress.getLng());
//                                        if (JYMathDoubleUtils.sub(distinctShop, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
//                                            orderSubmitResult.setSuccess(false);
//                                            orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
//                                            return orderSubmitResult;
//                                        }
//                                    }
                                    double distinctShop = Geohash.distance(shopInfo.getLat(), shopInfo.getLng(), userAddress.getLat(), userAddress.getLng());
                                    if (JYMathDoubleUtils.sub(distinctShop, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
                                        orderSubmitResult.setSuccess(false);
                                        orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                        return orderSubmitResult;
                                    }
                                }
                            } else if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && 0 == 2 - SYS_SETTINGS.IS_ELECTRONIC_FENCE) {// 是否启用电子围栏 0.不使用电子围栏 1.使用商圈电子围栏 2. 使用店铺电子围栏
                                // 判断该用户是否在店铺商圈内(多边形)
                                if (StringUtils.isEmpty(shopInfo.getLnglats())) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("店铺商圈经纬度无效，请联系客服");
                                    return orderSubmitResult;
                                }
                                String[] latlngs = shopInfo.getLnglats().split(";");
                                Double[] lngArr = new Double[latlngs.length];
                                Double[] latArr = new Double[latlngs.length];
                                for (int j = 0; j < latlngs.length; j++) {
                                    String[] lnla = latlngs[j].split(",");
                                    lngArr[j] = Double.parseDouble(lnla[0]);
                                    latArr[j] = Double.parseDouble(lnla[1]);
                                }
                                Boolean flag = Geohash.isInPolygon(userAddress.getLng(), userAddress.getLat(), lngArr, latArr);
                                if (!flag) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                    return orderSubmitResult;
                                }
                            } else {
                                if (ValidateUtil.isNotLatLng(cityAgent.getLat(), cityAgent.getLng())) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("店铺所在商圈未设置经纬度，请联系客服");
                                    return orderSubmitResult;
                                }
                                double distinct = Geohash.distance(cityAgent.getLat(), cityAgent.getLng(), userAddress.getLat(), userAddress.getLng());
                                if (JYMathDoubleUtils.sub(distinct, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("您选择的收货地址超出商圈的配送范围，请重新选择地址或联系客服。");
                                    return orderSubmitResult;
                                }
                                //验证收货地址距离店铺是否超出距离
                                if (null != shopInfo) {
//                                    if (SYS_SETTINGS.DELIVERY_DISTANCE_IS_NOT_CHECK != null && SYS_SETTINGS.DELIVERY_DISTANCE_IS_NOT_CHECK == 1) {
//                                        // 地址不验证收货地址
//                                    } else {
//                                        // 然后验证判断是否验证距离
//                                        double distinctShop = Geohash.distance(shopInfo.getLat(), shopInfo.getLng(), userAddress.getLat(), userAddress.getLng());
//                                        if (JYMathDoubleUtils.sub(distinctShop, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
//                                            orderSubmitResult.setSuccess(false);
//                                            orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
//                                            return orderSubmitResult;
//                                        }
//                                    }
                                    // 然后验证判断是否验证距离
                                    double distinctShop = Geohash.distance(shopInfo.getLat(), shopInfo.getLng(), userAddress.getLat(), userAddress.getLng());
                                    if (JYMathDoubleUtils.sub(distinctShop, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
                                        orderSubmitResult.setSuccess(false);
                                        orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                        return orderSubmitResult;
                                    }
                                }
                            }
                        }
                    }

                    //配送费计算方式
                    if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 2 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) { //配送费计算方式 1固定配送费 2 按距离（平台）计算 3按距离（店铺）
                        //2 按距离（平台）计算
                        if (ValidateUtil.isNotLatLng(userAddress.getLat(), userAddress.getLng())) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                            return orderSubmitResult;
                        }
                        //验证按距离计算的配送费是否正确
                        // Double distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离(店铺，收货地址)
                        Double distance = 0.0d;
                        if (SYS_SETTINGS.IS_RIDING_DISTANCE == 1) {
                            distance = ValidateUtil.isAbsDouble(ridingDistance) ? ridingDistance : 0.0d;
                        } else {
                            distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离(店铺，收货地址)
                        }
                        SysVariablePaotui sysVariablePaotui = SysVariablePaotuiMemory.getInstance().getByCode(7);
                        Double km = JYMathDoubleUtils.div(distance, 1000);
                        if (null != cityAgent) {
                            Integer postRange = cityAgent.getRang();
                            if (JYMathDoubleUtils.sub(km, postRange) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                        }

                        if (sysVariablePaotui != null) {
                            // 如果设置比列  则按照比例计算距离
                            if (SYS_SETTINGS.IS_RIDING_DISTANCE != 1 && SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
                                Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
                                distance = JYMathDoubleUtils.mul(distance, rate);
                            }
                            orderSubmitResult.setDistance(distance);
                            km = JYMathDoubleUtils.div(distance, 1000);
                            if (km - Double.parseDouble(sysVariablePaotui.getRang()) <= 0) {
                                String money = sysVariablePaotui.getVal();
                                if (ValidateUtil.isNotNull(money)) {
                                    deliveryPrice = Double.parseDouble(money);
                                }
                            } else {
//                                Double after = km - Double.parseDouble(sysVariablePaotui.getRang());
                                Double after = JYMathDoubleUtils.sub(km, Double.parseDouble(sysVariablePaotui.getRang()));
                                Double round = Math.ceil(after);
//                                String money = String.valueOf(Double.parseDouble(sysVariablePaotui.getVal()) + (round * Double.parseDouble(sysVariablePaotui.getPre())));
//                                if (ValidateUtil.isNotNull(money)) {
//                                    deliveryPrice = Double.parseDouble(money);
//                                }
                                deliveryPrice = JYMathDoubleUtils.add(Double.parseDouble(sysVariablePaotui.getVal()), JYMathDoubleUtils.mul(round, Double.parseDouble(sysVariablePaotui.getPre())));
                            }
                        } else {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("查不到配置参数");
                            return orderSubmitResult;
                        }
                    } else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 3 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
                        // 3按距离（店铺）
                        if (ValidateUtil.isNotLatLng(userAddress.getLat(), userAddress.getLng())) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                            return orderSubmitResult;
                        }
                        //验证按距离(店铺)计算的配送费是否正确
                        // Double distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
                        Double distance = 0.0d;
                        if (SYS_SETTINGS.IS_RIDING_DISTANCE == 1) {
                            distance = ValidateUtil.isAbsDouble(ridingDistance) ? ridingDistance : 0.0d;
                        } else {
                            distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
                        }
                        Double km = JYMathDoubleUtils.div(distance, 1000);//距离
                        if (null != cityAgent) {
                            Integer postRange = cityAgent.getRang();
                            if (JYMathDoubleUtils.sub(km, postRange) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                        }

                        //价格计算方式：基础配送费+上取整（实际下单距离-基础范围）*超出后每公里的价格

                        //v2 店铺没有这只规则的时候，使用平台的规则
                        //withinDistance 范围
                        Double withinDistance = shopInfo.getWithinDistance();
                        //fixedCost 范围内价格
                        Double fixedCost = shopInfo.getFixedCost();
                        //oneKmCost 超出后每公里价格
                        Double oneKmCost = shopInfo.getOneKmCost();
                        if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                            //店铺未设置规则
                            //查看商圈的公式值
                            if (null == cityAgent) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("配送费规则设置的不正确，请联系客服");
                                return orderSubmitResult;
                            }
                            // 指定是时间段的
                            CityAgentFeeMan.assignmentCityAgentFeeByTime(cityAgent, DateUtils.getCurrTime());
                            //withinDistance 范围
                            withinDistance = cityAgent.getWithinDistance();
                            //fixedCost 范围内价格
                            fixedCost = cityAgent.getFixedCost();
                            //oneKmCost 超出后每公里价格
                            oneKmCost = cityAgent.getOneKmCost();
                        }
                        if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                            //不收配送费
                        } else {
                            // 如果设置比列  则按照比例计算距离
                            if (SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
                                Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
                                distance = JYMathDoubleUtils.mul(distance, rate);
                            }
                            km = JYMathDoubleUtils.div(distance, 1000);//距离
                            if (km - withinDistance <= 0) {
                                deliveryPrice = fixedCost;
                            } else {
//                                Double after = km - withinDistance;
                                Double after = JYMathDoubleUtils.sub(km, withinDistance);
                                Double round = Math.ceil(after);
//                                deliveryPrice = fixedCost + round * oneKmCost;
                                deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
                            }
                        }
                        orderSubmitResult.setDistance(distance);

//                        //v1 只按店铺的规则
//                        if (shopInfo.getFixedCost() != null && shopInfo.getOneKmCost() != null && shopInfo.getWithinDistance() != null) {
//                            if (km - shopInfo.getWithinDistance() <= 0) {
//                                deliveryPrice = shopInfo.getFixedCost();
//                            } else {
//                                Double after = km - shopInfo.getWithinDistance();
//                                Double round = Math.ceil(after);
//                                deliveryPrice = shopInfo.getFixedCost() + round * shopInfo.getOneKmCost();
//                            }
//                        } else {
//                            orderSubmitResult.setSuccess(false);
//                            orderSubmitResult.setError("查不到配置参数");
//                            return orderSubmitResult;
//                        }


                    }
//                    else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 4 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
//                        // 4按商圈设置的时间段进行判断
//                        // 验证按距离(店铺)计算的配送费是否正确
//                        Double distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
//                        // 如果设置比列  则按照比例计算距离
//                        if (SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
//                            Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
//                            distance = JYMathDoubleUtils.mul(distance, rate);
//                        }
//                        Double km = JYMathDoubleUtils.div(distance, 1000);//距离
//                        //价格计算方式：基础配送费+上取整（实际下单距离-基础范围）*超出后每公里的价格
//
//                        CityAgentFeeInfo info = CityAgentFeeMan.getCityAgentFeeByTime(cityAgent.getId(), DateUtils.getCurrTime());
//                        if (info == null) {
//                            orderSubmitResult.setSuccess(false);
//                            orderSubmitResult.setError("当前商圈尚未设置费用,请重新选择地址或联系客服。");
//                            return orderSubmitResult;
//                        }
//                        //withinDistance 范围
//                        Double withinDistance = info.getWithinDistance();
//                        //fixedCost 范围内价格
//                        Double fixedCost = info.getFixedCost();
//                        //oneKmCost 超出后每公里价格
//                        Double oneKmCost = info.getOneKmCost();
//                        if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
//                            //不收配送费
//                        } else {
//                            if (km - withinDistance <= 0) {
//                                deliveryPrice = fixedCost;
//                            } else {
//                                Double after = JYMathDoubleUtils.sub(km, withinDistance);
//                                Double round = Math.ceil(after);
//                                deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
//                            }
//                        }
//                    }
                } else { //传入经纬度方式
                    if (null != SYS_SETTINGS.USER_ADDRESS_IS_AGENT && 0 != 1 - SYS_SETTINGS.USER_ADDRESS_IS_AGENT) {
                        Integer postRange = cityAgent.getRang();
                        if (ValidateUtil.isNotAbsInteger(postRange)) {
                            postRange = 0;
                        }

                        // 是否启用电子围栏 0.不使用电子围栏 1.使用电子围栏
                        if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && 0 == 1 - SYS_SETTINGS.IS_ELECTRONIC_FENCE) {
                            // 判断该用户是否在商圈内(多边形)
                            if (StringUtils.isEmpty(cityAgent.getLnglats())) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("商圈经纬度无效，请联系客服");
                                return orderSubmitResult;
                            }
                            String[] latlngs = cityAgent.getLnglats().split(";");
                            Double[] lngArr = new Double[latlngs.length];
                            Double[] latArr = new Double[latlngs.length];
                            for (int j = 0; j < latlngs.length; j++) {
                                String[] lnla = latlngs[j].split(",");
                                lngArr[j] = Double.parseDouble(lnla[0]);
                                latArr[j] = Double.parseDouble(lnla[1]);
                            }
                            if (ValidateUtil.isNotLatLng(userAddress.getLat(), userAddress.getLng())) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该商圈的配送范围，请重新选择地址或联系客服");
                                return orderSubmitResult;
                            }
                            Boolean flag = Geohash.isInPolygon(userAddress.getLng(), userAddress.getLat(), lngArr, latArr);
                            if (!flag) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该商圈的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                        } else if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && 0 == 2 - SYS_SETTINGS.IS_ELECTRONIC_FENCE) {// 是否启用电子围栏 0.不使用电子围栏 1.使用商圈电子围栏 2. 使用店铺电子围栏
                            // 判断该用户是否在店铺商圈内(多边形)
                            if (StringUtils.isEmpty(shopInfo.getLnglats())) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("店铺商圈经纬度无效，请联系客服");
                                return orderSubmitResult;
                            }
                            String[] latlngs = shopInfo.getLnglats().split(";");
                            Double[] lngArr = new Double[latlngs.length];
                            Double[] latArr = new Double[latlngs.length];
                            for (int j = 0; j < latlngs.length; j++) {
                                String[] lnla = latlngs[j].split(",");
                                lngArr[j] = Double.parseDouble(lnla[0]);
                                latArr[j] = Double.parseDouble(lnla[1]);
                            }
                            Boolean flag = Geohash.isInPolygon(userAddress.getLng(), userAddress.getLat(), lngArr, latArr);
                            if (!flag) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                        } else {
                            if (ValidateUtil.isNotLatLng(cityAgent.getLat(), cityAgent.getLng())) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("店铺所在商圈未设置经纬度，请联系客服");
                                return orderSubmitResult;
                            }
                            //验证收货距离
                            double distinct = Geohash.distance(cityAgent.getLat(), cityAgent.getLng(), buyLat, buyLng);
                            if (JYMathDoubleUtils.sub(distinct, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                        }


                        if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 2 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) { //配送费计算方式 1固定配送费
                            // 2按距离计算(平台)
                            if (ValidateUtil.isNotLatLng(buyLat, buyLng)) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                                return orderSubmitResult;
                            }

                            //验证按距离计算的配送费是否正确
                            // Double distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                            Double distance = 0.0d;
                            if (SYS_SETTINGS.IS_RIDING_DISTANCE == 1) {
                                distance = ValidateUtil.isAbsDouble(ridingDistance) ? ridingDistance : 0.0d;
                            } else {
                                distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                            }
                            SysVariablePaotui sysVariablePaotui = SysVariablePaotuiMemory.getInstance().getByCode(7);
                            Double km = JYMathDoubleUtils.div(distance, 1000);
                            //验证收货地址距离店铺是否超出距离
                            if (JYMathDoubleUtils.sub(km, postRange) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }

                            if (sysVariablePaotui != null) {
                                // 如果设置比列  则按照比例计算距离配送费
                                if (SYS_SETTINGS.IS_RIDING_DISTANCE != 1 && SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
                                    Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
                                    distance = JYMathDoubleUtils.mul(distance, rate);
                                }
                                orderSubmitResult.setDistance(distance);
                                km = JYMathDoubleUtils.div(distance, 1000);//距离
                                if (km - Double.parseDouble(sysVariablePaotui.getRang()) <= 0) {
                                    String money = sysVariablePaotui.getVal();
                                    if (ValidateUtil.isNotNull(money)) {
                                        deliveryPrice = Double.parseDouble(money);
                                    }
                                } else {
//                                    Double after = km - Double.parseDouble(sysVariablePaotui.getRang());
                                    Double after = JYMathDoubleUtils.sub(km, Double.parseDouble(sysVariablePaotui.getRang()));
                                    Double round = Math.ceil(after);
//                                    String money = String.valueOf(Double.parseDouble(sysVariablePaotui.getVal()) + (round * Double.parseDouble(sysVariablePaotui.getPre())));
//                                    if (ValidateUtil.isNotNull(money)) {
//                                        deliveryPrice = Double.parseDouble(money);
//                                    }
                                    deliveryPrice = JYMathDoubleUtils.add(Double.parseDouble(sysVariablePaotui.getVal()), JYMathDoubleUtils.mul(round, Double.parseDouble(sysVariablePaotui.getPre())));
                                }
                            } else {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("查不到配置参数");
                                return orderSubmitResult;
                            }
                        } else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 3 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
                            // 3按距离（店铺）
                            if (ValidateUtil.isNotLatLng(buyLat, buyLng)) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                                return orderSubmitResult;
                            }

                            //验证按距离(店铺)计算的配送费是否正确
                            // Double distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                            Double distance = 0.0D;
                            if (SYS_SETTINGS.IS_RIDING_DISTANCE == 1) {
                                distance = ValidateUtil.isAbsDouble(ridingDistance) ? ridingDistance : 0.0d;
                            } else {
                                distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                            }
                            Double km = JYMathDoubleUtils.div(distance, 1000);
                            //验证收货地址距离店铺是否超出距离
                            if (JYMathDoubleUtils.sub(km, postRange) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }


                            //v2 店铺没有这只规则的时候，使用平台的规则
                            //withinDistance 范围
                            Double withinDistance = shopInfo.getWithinDistance();
                            //fixedCost 范围内价格
                            Double fixedCost = shopInfo.getFixedCost();
                            //oneKmCost 超出后每公里价格
                            Double oneKmCost = shopInfo.getOneKmCost();
                            if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                                //店铺未设置规则
                                //查看商圈的公式值
                                if (null == cityAgent) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("配送费规则设置的不正确，请联系客服");
                                    return orderSubmitResult;
                                }
                                // 指定是时间段的
                                CityAgentFeeMan.assignmentCityAgentFeeByTime(cityAgent, DateUtils.getCurrTime());
                                //withinDistance 范围
                                withinDistance = cityAgent.getWithinDistance();
                                //fixedCost 范围内价格
                                fixedCost = cityAgent.getFixedCost();
                                //oneKmCost 超出后每公里价格
                                oneKmCost = cityAgent.getOneKmCost();
                            }
                            if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                                //不收配送费
                            } else {
                                // 如果设置比列  则按照比例计算距离配送费
                                if (SYS_SETTINGS.IS_RIDING_DISTANCE != 1 && SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
                                    Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
                                    distance = JYMathDoubleUtils.mul(distance, rate);
                                }
                                km = JYMathDoubleUtils.div(distance, 1000);//距离
                                if (km - withinDistance <= 0) {
                                    deliveryPrice = fixedCost;
                                } else {
                                    Double after = km - withinDistance;
                                    Double round = Math.ceil(after);
//                                    deliveryPrice = fixedCost + round * oneKmCost;
                                    deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
                                }
                            }
                            orderSubmitResult.setDistance(distance);

//                        //v1 只按店铺的规则
//                            if (shopInfo.getFixedCost() != null && shopInfo.getOneKmCost() != null && shopInfo.getWithinDistance() != null) {
//
//                                if (km - shopInfo.getWithinDistance() <= 0) {
//                                    deliveryPrice = shopInfo.getFixedCost();
//                                } else {
//                                    Double after = km - shopInfo.getWithinDistance();
//                                    Double round = Math.ceil(after);
//                                    deliveryPrice = shopInfo.getFixedCost() + round * shopInfo.getOneKmCost();
//                                }
//                            } else {
//                                orderSubmitResult.setSuccess(false);
//                                orderSubmitResult.setError("查不到配置参数");
//                                return orderSubmitResult;
//                            }
                        }
//                        else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 4 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
//                            // 4按商圈设置的时间段进行判断
//                            // 验证按距离(店铺)计算的配送费是否正确
//                            Double distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
//                            // 如果设置比列  则按照比例计算距离
//                            if (SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
//                                Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
//                                distance = JYMathDoubleUtils.mul(distance, rate);
//                            }
//                            Double km = JYMathDoubleUtils.div(distance, 1000);//距离
//                            //价格计算方式：基础配送费+上取整（实际下单距离-基础范围）*超出后每公里的价格
//
//                            CityAgentFeeInfo info = CityAgentFeeMan.getCityAgentFeeByTime(cityAgent.getId(), DateUtils.getCurrTime());
//                            if (info == null) {
//                                orderSubmitResult.setSuccess(false);
//                                orderSubmitResult.setError("当前商圈尚未设置费用,请重新选择地址或联系客服。");
//                                return orderSubmitResult;
//                            }
//                            //withinDistance 范围
//                            Double withinDistance = info.getWithinDistance();
//                            //fixedCost 范围内价格
//                            Double fixedCost = info.getFixedCost();
//                            //oneKmCost 超出后每公里价格
//                            Double oneKmCost = info.getOneKmCost();
//                            if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
//                                //不收配送费
//                            } else {
//                                if (km - withinDistance <= 0) {
//                                    deliveryPrice = fixedCost;
//                                } else {
//                                    Double after = JYMathDoubleUtils.sub(km, withinDistance);
//                                    Double round = Math.ceil(after);
//                                    deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
//                                }
//                            }
//                        }

                    }
                }
            } else if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && 0 == 2 - SYS_SETTINGS.IS_ELECTRONIC_FENCE) {// 是否启用电子围栏 0.不使用电子围栏 1.使用商圈电子围栏 2. 使用店铺电子围栏
                // 判断该用户是否在店铺商圈内(多边形)
                if (StringUtils.isEmpty(shopInfo.getLnglats())) {
                    orderSubmitResult.setSuccess(false);
                    orderSubmitResult.setError("店铺商圈经纬度无效，请联系客服");
                    return orderSubmitResult;
                }
                String[] latlngs = shopInfo.getLnglats().split(";");
                Double[] lngArr = new Double[latlngs.length];
                Double[] latArr = new Double[latlngs.length];
                for (int j = 0; j < latlngs.length; j++) {
                    String[] lnla = latlngs[j].split(",");
                    lngArr[j] = Double.parseDouble(lnla[0]);
                    latArr[j] = Double.parseDouble(lnla[1]);
                }
                Boolean flag = Geohash.isInPolygon(userAddress.getLng(), userAddress.getLat(), lngArr, latArr);
                if (!flag) {
                    orderSubmitResult.setSuccess(false);
                    orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                    return orderSubmitResult;
                }
            }
        }
        orderSubmitResult.setOrderDeliveryPrice(deliveryPrice);
        return orderSubmitResult;
    }

    // 说明 吃啥外卖 店铺地址在多个商圈内  颜真的商圈可能不是一个 ，为了不影响主版本的控制 所有创建了副本
    //配送费处理(新增围栏模式)
    private static OrderSubmitResult doDeliveryPriceV2(Integer isZiQu, ShopInfo shopInfo,
                                                       UserAddress userAddress, Long agentId,
                                                       CityAgent cityAgent, Double deliveryPrice,
                                                       Double buyLat, Double buyLng,
                                                       List<Long> agentIdList,
                                                       Double ridingDistance,
                                                       OrderSubmitResult orderSubmitResult) {
        if (null != isZiQu && 0 == isZiQu) { //需要配送
            if (ValidateUtil.isNotLatLng(shopInfo.getLat(), shopInfo.getLng())) {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("店铺位置信息不准确，请联系客服");
                return orderSubmitResult;
            }
            //验证配送范围
            if (null != SYS_SETTINGS.SHOP_MANAGE_TYPE && 0 == SHOP_MANAGE_TYPE_FREE_OR_AGENT.AGENT - SYS_SETTINGS.SHOP_MANAGE_TYPE) {
                //如果是按学校这种精确配送员的  需要验证店铺对应的收货地址是在同一个范围内吗
                if (null != userAddress) { //收货地址方式
                    if (ValidateUtil.isNotLatLng(userAddress.getLat(), userAddress.getLng())) {
                        orderSubmitResult.setSuccess(false);
                        orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                        return orderSubmitResult;
                    }
                    if (ValidateUtil.isAbsLong(userAddress.getAgentId())) {//地址里有代理
                        if (0 != userAddress.getAgentId() - agentId) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服");
                            return orderSubmitResult;
                        }
                    } else { //地址里没有代理  验证用户的收货地址，是否在店铺所在代理的配送范围
                        if (null != SYS_SETTINGS.USER_ADDRESS_IS_AGENT && 0 != 1 - SYS_SETTINGS.USER_ADDRESS_IS_AGENT) {
                            Integer postRange = 0;
                            if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && 0 == 1 - SYS_SETTINGS.IS_ELECTRONIC_FENCE) {    // 是否启用电子围栏 0.不使用电子围栏 1.使用电子围栏
                                if (SYS_SETTINGS.SHOP_BELONG_MULTIPLE_AGENT == 1) {
                                    if (agentIdList == null && agentIdList.isEmpty()
                                            && Optional.ofNullable(shopInfo).map(ShopInfo::getId).isPresent()) {
                                        agentIdList = ShopAgentRelationMemory.getInstance().agentListOfShopId(shopInfo.getId());
                                    }
                                    if (agentIdList == null && agentIdList.isEmpty()) {
                                        orderSubmitResult.setSuccess(false);
                                        orderSubmitResult.setError("店铺没有服务的商圈");
                                        return orderSubmitResult;
                                    }
                                    // 获取一个有效的agent
                                    cityAgent = getValidCityAgent(agentIdList, shopInfo, userAddress.getLng(), userAddress.getLat());
                                    if (cityAgent == null) {
                                        orderSubmitResult.setSuccess(false);
                                        orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                        return orderSubmitResult;
                                    }
                                    postRange = cityAgent.getRang() == null ? 0 : cityAgent.getRang();
                                } else {
                                    if (cityAgent == null) {
                                        orderSubmitResult.setSuccess(false);
                                        orderSubmitResult.setError("商圈信息为空，请联系客服");
                                        return orderSubmitResult;
                                    }
                                    postRange = cityAgent.getRang();
                                    if (ValidateUtil.isNotAbsInteger(postRange)) {
                                        postRange = 0;
                                    }
                                    // 判断该用户是否在商圈内(多边形)
                                    if (StringUtils.isEmpty(cityAgent.getLnglats())) {
                                        orderSubmitResult.setSuccess(false);
                                        orderSubmitResult.setError("商圈经纬度无效，请联系客服");
                                        return orderSubmitResult;
                                    }
                                    if (!checkInCityAgentFence(shopInfo, cityAgent, userAddress.getLat(), userAddress.getLng())) {
                                        orderSubmitResult.setSuccess(false);
                                        orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                        return orderSubmitResult;
                                    }
                                }
                            } else if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && 0 == 2 - SYS_SETTINGS.IS_ELECTRONIC_FENCE) { // 是否启用电子围栏 0.不使用电子围栏 1.使用商圈电子围栏 2. 使用店铺电子围栏
                                if (SYS_SETTINGS.SHOP_BELONG_MULTIPLE_AGENT == 1) {
                                    if (agentIdList == null && agentIdList.isEmpty()
                                            && Optional.ofNullable(shopInfo).map(ShopInfo::getId).isPresent()) {
                                        agentIdList = ShopAgentRelationMemory.getInstance().agentListOfShopId(shopInfo.getId());
                                    }
                                    if (agentIdList == null && agentIdList.isEmpty()) {
                                        orderSubmitResult.setSuccess(false);
                                        orderSubmitResult.setError("店铺没有服务的商圈");
                                        return orderSubmitResult;
                                    }
                                    // 获取一个有效的agent
                                    cityAgent = getValidCityAgent(agentIdList, shopInfo, userAddress.getLng(), userAddress.getLat());
                                    if (cityAgent == null) {
                                        orderSubmitResult.setSuccess(false);
                                        orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                        return orderSubmitResult;
                                    }
                                    postRange = cityAgent.getRang() == null ? 0 : cityAgent.getRang();
                                } else {
                                    if (cityAgent == null) {
                                        orderSubmitResult.setSuccess(false);
                                        orderSubmitResult.setError("商圈信息为空，请联系客服");
                                        return orderSubmitResult;
                                    }
                                    postRange = cityAgent.getRang();
                                    if (ValidateUtil.isNotAbsInteger(postRange)) {
                                        postRange = 0;
                                    }
                                    // 判断该用户是否在商圈内(多边形)
                                    if (StringUtils.isEmpty(cityAgent.getLnglats())) {
                                        orderSubmitResult.setSuccess(false);
                                        orderSubmitResult.setError("商圈经纬度无效，请联系客服");
                                        return orderSubmitResult;
                                    }
                                    if (!checkInCityAgentFence(shopInfo, cityAgent, userAddress.getLat(), userAddress.getLng())) {
                                        orderSubmitResult.setSuccess(false);
                                        orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                        return orderSubmitResult;
                                    }
                                }
                                // 判断该用户是否在店铺商圈内(多边形)
                                if (!checkInCityShopFence(shopInfo, userAddress.getLat(), userAddress.getLng())) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                    return orderSubmitResult;
                                }
                            } else {
                                if (cityAgent == null) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("店铺所在商圈未获取到，请联系客服");
                                    return orderSubmitResult;
                                }
                                if (ValidateUtil.isNotLatLng(cityAgent.getLat(), cityAgent.getLng())) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("店铺所在商圈未设置经纬度，请联系客服");
                                    return orderSubmitResult;
                                }
                                postRange = cityAgent.getRang();
                                if (ValidateUtil.isNotAbsInteger(postRange)) {
                                    postRange = 0;
                                }
                                if (!checkPostRange(cityAgent.getLat(), cityAgent.getLng(), userAddress.getLat(), userAddress.getLng(), postRange)) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("您选择的收货地址超出商圈的配送范围，请重新选择地址或联系客服。");
                                    return orderSubmitResult;
                                }
                                //验证收货地址距离店铺是否超出距离
                                if (null != shopInfo && !checkPostRange(shopInfo.getLat(), shopInfo.getLng(), userAddress.getLat(), userAddress.getLng(), postRange)) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                    return orderSubmitResult;
                                }
                            }
                        }
                    }
                    //配送费计算方式
                    if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 2 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {  //配送费计算方式 1固定配送费 2 按距离（平台）计算 3按距离（店铺）
                        //2 按距离（平台）计算
                        //验证按距离计算的配送费是否正确
                        Double distance = 0.0d;
                        if (SYS_SETTINGS.IS_RIDING_DISTANCE == 1) {
                            distance = ValidateUtil.isAbsDouble(ridingDistance) ? ridingDistance : 0.0d;
                        } else {
                            distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng()); //根据两点的经纬度计算距离(店铺，收货地址)
                            // 如果设置比列  则按照比例计算距离
                            if (SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
                                Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
                                distance = JYMathDoubleUtils.mul(distance, rate);
                            }
                        }
                        orderSubmitResult.setDistance(distance);
                        SysVariablePaotui sysVariablePaotui = SysVariablePaotuiMemory.getInstance().getByCode(7);
                        Double km = JYMathDoubleUtils.div(distance, 1000);
                        if (sysVariablePaotui != null) {
                            if (km - Double.parseDouble(sysVariablePaotui.getRang()) <= 0) {
                                String money = sysVariablePaotui.getVal();
                                if (ValidateUtil.isNotNull(money)) {
                                    deliveryPrice = Double.parseDouble(money);
                                }
                            } else {
                                Double after = JYMathDoubleUtils.sub(km, Double.parseDouble(sysVariablePaotui.getRang()));
                                Double round = Math.ceil(after);
                                deliveryPrice = JYMathDoubleUtils.add(Double.parseDouble(sysVariablePaotui.getVal()), JYMathDoubleUtils.mul(round, Double.parseDouble(sysVariablePaotui.getPre())));
                            }
                        } else {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("查不到配置参数");
                            return orderSubmitResult;
                        }
                    } else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 3 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
                        // 3按距离（店铺）
                        //验证按距离(店铺)计算的配送费是否正确
                        Double distance = 0.0d;
                        if (SYS_SETTINGS.IS_RIDING_DISTANCE == 1) {
                            distance = ValidateUtil.isAbsDouble(ridingDistance) ? ridingDistance : 0.0d;
                        } else {
                            distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
                            // 如果设置比列  则按照比例计算距离
                            if (SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
                                Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
                                distance = JYMathDoubleUtils.mul(distance, rate);
                            }
                        }
                        // Double distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
                        orderSubmitResult.setDistance(distance);
                        Double km = JYMathDoubleUtils.div(distance, 1000);//距离
                        //价格计算方式：基础配送费+上取整（实际下单距离-基础范围）*超出后每公里的价格

                        //v2 店铺没有这只规则的时候，使用平台的规则
                        //withinDistance 范围
                        Double withinDistance = shopInfo.getWithinDistance();
                        //fixedCost 范围内价格
                        Double fixedCost = shopInfo.getFixedCost();
                        //oneKmCost 超出后每公里价格
                        Double oneKmCost = shopInfo.getOneKmCost();
                        if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                            // 指定是时间段的
                            CityAgentFeeMan.assignmentCityAgentFeeByTime(cityAgent, DateUtils.getCurrTime());
                            //店铺未设置规则
                            //查看商圈的公式值
                            //withinDistance 范围
                            withinDistance = cityAgent.getWithinDistance();
                            //fixedCost 范围内价格
                            fixedCost = cityAgent.getFixedCost();
                            //oneKmCost 超出后每公里价格
                            oneKmCost = cityAgent.getOneKmCost();
                        }
                        if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                            //不收配送费
                        } else {
                            if (km - withinDistance <= 0) {
                                deliveryPrice = fixedCost;
                            } else {
                                Double after = JYMathDoubleUtils.sub(km, withinDistance);
                                Double round = Math.ceil(after);
                                deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
                            }
                        }
                    }
//                    else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 5 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
//                        // 4按商圈设置的时间段进行判断
//                        // 验证按距离(店铺)计算的配送费是否正确
//                        Double distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
//                        // 如果设置比列  则按照比例计算距离
//                        if (SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
//                            Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
//                            distance = JYMathDoubleUtils.mul(distance, rate);
//                        }
//                        Double km = JYMathDoubleUtils.div(distance, 1000);//距离
//                        //价格计算方式：基础配送费+上取整（实际下单距离-基础范围）*超出后每公里的价格
//
//                        CityAgentFeeInfo info = CityAgentFeeMan.getCityAgentFeeByTime(cityAgent.getId(), DateUtils.getCurrTime());
//                        if (info == null) {
//                            orderSubmitResult.setSuccess(false);
//                            orderSubmitResult.setError("当前商圈尚未设置费用,请重新选择地址或联系客服。");
//                            return orderSubmitResult;
//                        }
//                        //withinDistance 范围
//                        Double withinDistance = info.getWithinDistance();
//                        //fixedCost 范围内价格
//                        Double fixedCost = info.getFixedCost();
//                        //oneKmCost 超出后每公里价格
//                        Double oneKmCost = info.getOneKmCost();
//                        if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
//                            //不收配送费
//                        } else {
//                            if (km - withinDistance <= 0) {
//                                deliveryPrice = fixedCost;
//                            } else {
//                                Double after = JYMathDoubleUtils.sub(km, withinDistance);
//                                Double round = Math.ceil(after);
//                                deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
//                            }
//                        }
//                    }
                } else { //传入经纬度方式
//                    if(ValidateUtil.isNotLatLng())
                    if (ValidateUtil.isNotLatLng(buyLat, buyLng)) {
                        orderSubmitResult.setSuccess(false);
                        orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                        return orderSubmitResult;
                    }
                    if (null != SYS_SETTINGS.USER_ADDRESS_IS_AGENT && 0 != 1 - SYS_SETTINGS.USER_ADDRESS_IS_AGENT) {
                        Integer postRange = 0;
                        // 是否启用电子围栏 0.不使用电子围栏 1.使用电子围栏
                        if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && 0 == 1 - SYS_SETTINGS.IS_ELECTRONIC_FENCE) {
                            if (SYS_SETTINGS.SHOP_BELONG_MULTIPLE_AGENT == 1) {
                                if (agentIdList == null && agentIdList.isEmpty()
                                        && Optional.ofNullable(shopInfo).map(ShopInfo::getId).isPresent()) {
                                    agentIdList = ShopAgentRelationMemory.getInstance().agentListOfShopId(shopInfo.getId());
                                }
                                if (agentIdList == null && agentIdList.isEmpty()) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("店铺没有服务的商圈");
                                    return orderSubmitResult;
                                }
                                // 获取一个有效的agent
                                cityAgent = getValidCityAgent(agentIdList, shopInfo, buyLng, buyLat);
                                if (cityAgent == null) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                    return orderSubmitResult;
                                }
                                postRange = cityAgent.getRang() == null ? 0 : cityAgent.getRang();
                            } else {
                                if (cityAgent == null) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("商圈信息为空，请联系客服");
                                    return orderSubmitResult;
                                }
                                postRange = cityAgent.getRang();
                                if (ValidateUtil.isNotAbsInteger(postRange)) {
                                    postRange = 0;
                                }
                                // 判断该用户是否在商圈内(多边形)
                                if (StringUtils.isEmpty(cityAgent.getLnglats())) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("商圈经纬度无效，请联系客服");
                                    return orderSubmitResult;
                                }
                                if (!checkInCityAgentFence(shopInfo, cityAgent, buyLat, buyLng)) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                    return orderSubmitResult;
                                }
                            }
                        } else if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && 0 == 2 - SYS_SETTINGS.IS_ELECTRONIC_FENCE) {// 是否启用电子围栏 0.不使用电子围栏 1.使用商圈电子围栏 2. 使用店铺电子围栏
                            if (SYS_SETTINGS.SHOP_BELONG_MULTIPLE_AGENT == 1) {
                                if (agentIdList == null && agentIdList.isEmpty()
                                        && Optional.ofNullable(shopInfo).map(ShopInfo::getId).isPresent()) {
                                    agentIdList = ShopAgentRelationMemory.getInstance().agentListOfShopId(shopInfo.getId());
                                }
                                if (agentIdList == null && agentIdList.isEmpty()) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("店铺没有服务的商圈");
                                    return orderSubmitResult;
                                }
                                // 获取一个有效的agent
                                cityAgent = getValidCityAgent(agentIdList, shopInfo, buyLng, buyLat);
                                if (cityAgent == null) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                    return orderSubmitResult;
                                }
                                postRange = cityAgent.getRang() == null ? 0 : cityAgent.getRang();
                            } else {
                                if (cityAgent == null) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("商圈信息为空，请联系客服");
                                    return orderSubmitResult;
                                }
                                postRange = cityAgent.getRang();
                                if (ValidateUtil.isNotAbsInteger(postRange)) {
                                    postRange = 0;
                                }
                                // 判断该用户是否在商圈内(多边形)
                                if (StringUtils.isEmpty(cityAgent.getLnglats())) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("商圈经纬度无效，请联系客服");
                                    return orderSubmitResult;
                                }
                                if (!checkInCityAgentFence(shopInfo, cityAgent, buyLat, buyLng)) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                    return orderSubmitResult;
                                }
                            }
                            // 判断该用户是否在店铺商圈内(多边形)
                            if (!checkInCityShopFence(shopInfo, buyLat, buyLng)) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                        } else {
                            if (cityAgent == null) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("店铺所在商圈未获取到，请联系客服");
                                return orderSubmitResult;
                            }
                            if (ValidateUtil.isNotLatLng(cityAgent.getLat(), cityAgent.getLng())) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("店铺所在商圈未设置经纬度，请联系客服");
                                return orderSubmitResult;
                            }
                            postRange = cityAgent.getRang();
                            if (ValidateUtil.isNotAbsInteger(postRange)) {
                                postRange = 0;
                            }
                            if (!checkPostRange(cityAgent.getLat(), cityAgent.getLng(), userAddress.getLat(), userAddress.getLng(), postRange)) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出商圈的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                            //验证收货地址距离店铺是否超出距离
                            if (null != shopInfo && !checkPostRange(shopInfo.getLat(), shopInfo.getLng(), buyLat, buyLng, postRange)) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                        }
                        if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 2 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) { //配送费计算方式 1固定配送费
                            // 2按距离计算(平台)
                            //验证按距离计算的配送费是否正确
                            // Double distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                            Double distance = 0.0d;
                            if (SYS_SETTINGS.IS_RIDING_DISTANCE == 1) {
                                distance = ValidateUtil.isAbsDouble(ridingDistance) ? ridingDistance : 0.0d;
                            } else {
                                distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                                // 如果设置比列  则按照比例计算距离
                                if (SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
                                    Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
                                    distance = JYMathDoubleUtils.mul(distance, rate);
                                }
                            }
                            orderSubmitResult.setDistance(distance);
                            SysVariablePaotui sysVariablePaotui = SysVariablePaotuiMemory.getInstance().getByCode(7);
                            Double km = JYMathDoubleUtils.div(distance, 1000);
                            if (sysVariablePaotui != null) {
                                if (km - Double.parseDouble(sysVariablePaotui.getRang()) <= 0) {
                                    String money = sysVariablePaotui.getVal();
                                    if (ValidateUtil.isNotNull(money)) {
                                        deliveryPrice = Double.parseDouble(money);
                                    }
                                } else {
                                    Double after = JYMathDoubleUtils.sub(km, Double.parseDouble(sysVariablePaotui.getRang()));
                                    Double round = Math.ceil(after);
                                    deliveryPrice = JYMathDoubleUtils.add(Double.parseDouble(sysVariablePaotui.getVal()), JYMathDoubleUtils.mul(round, Double.parseDouble(sysVariablePaotui.getPre())));
                                }
                            } else {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("查不到配置参数");
                                return orderSubmitResult;
                            }
                        } else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 3 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
                            // 3按距离（店铺）
                            //验证按距离(店铺)计算的配送费是否正确
                            // Double distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                            Double distance = 0.0d;
                            if (SYS_SETTINGS.IS_RIDING_DISTANCE == 1) {
                                distance = ValidateUtil.isAbsDouble(ridingDistance) ? ridingDistance : 0.0d;
                            } else {
                                distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                                // 如果设置比列  则按照比例计算距离
                                if (SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
                                    Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
                                    distance = JYMathDoubleUtils.mul(distance, rate);
                                }
                            }
                            orderSubmitResult.setDistance(distance);
                            Double km = JYMathDoubleUtils.div(distance, 1000);
                            //v2 店铺没有这只规则的时候，使用平台的规则
                            //withinDistance 范围
                            Double withinDistance = shopInfo.getWithinDistance();
                            //fixedCost 范围内价格
                            Double fixedCost = shopInfo.getFixedCost();
                            //oneKmCost 超出后每公里价格
                            Double oneKmCost = shopInfo.getOneKmCost();
                            if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                                //店铺未设置规则
                                //查看商圈的公式值
                                if (null == cityAgent) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("配送费规则设置的不正确，请联系客服");
                                    return orderSubmitResult;
                                }
                                // 指定是时间段的
                                CityAgentFeeMan.assignmentCityAgentFeeByTime(cityAgent, DateUtils.getCurrTime());
                                //withinDistance 范围
                                withinDistance = cityAgent.getWithinDistance();
                                //fixedCost 范围内价格
                                fixedCost = cityAgent.getFixedCost();
                                //oneKmCost 超出后每公里价格
                                oneKmCost = cityAgent.getOneKmCost();
                            }
                            if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                                //不收配送费
                            } else {
                                if (km - withinDistance <= 0) {
                                    deliveryPrice = fixedCost;
                                } else {
                                    Double after = km - withinDistance;
                                    Double round = Math.ceil(after);
                                    deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
                                }
                            }
                        }
//                        else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 4 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
//                            // 4按商圈设置的时间段进行判断
//                            // 验证按距离(店铺)计算的配送费是否正确
//                            Double distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
//                            // 如果设置比列  则按照比例计算距离
//                            if (SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
//                                Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
//                                distance = JYMathDoubleUtils.mul(distance, rate);
//                            }
//                            Double km = JYMathDoubleUtils.div(distance, 1000);//距离
//                            //价格计算方式：基础配送费+上取整（实际下单距离-基础范围）*超出后每公里的价格
//
//                            CityAgentFeeInfo info = CityAgentFeeMan.getCityAgentFeeByTime(cityAgent.getId(), DateUtils.getCurrTime());
//                            if (info == null) {
//                                orderSubmitResult.setSuccess(false);
//                                orderSubmitResult.setError("当前商圈尚未设置费用,请重新选择地址或联系客服。");
//                                return orderSubmitResult;
//                            }
//                            //withinDistance 范围
//                            Double withinDistance = info.getWithinDistance();
//                            //fixedCost 范围内价格
//                            Double fixedCost = info.getFixedCost();
//                            //oneKmCost 超出后每公里价格
//                            Double oneKmCost = info.getOneKmCost();
//                            if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
//                                //不收配送费
//                            } else {
//                                if (km - withinDistance <= 0) {
//                                    deliveryPrice = fixedCost;
//                                } else {
//                                    Double after = JYMathDoubleUtils.sub(km, withinDistance);
//                                    Double round = Math.ceil(after);
//                                    deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
//                                }
//                            }
//                        }

                    }
                }
                // 下面这个逻辑实在是没看懂  再次记录
            } else if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && 0 == 2 - SYS_SETTINGS.IS_ELECTRONIC_FENCE) {// 是否启用电子围栏 0.不使用电子围栏 1.使用商圈电子围栏 2. 使用店铺电子围栏
                // 判断该用户是否在店铺商圈内(多边形)
                if (StringUtils.isEmpty(shopInfo.getLnglats())) {
                    orderSubmitResult.setSuccess(false);
                    orderSubmitResult.setError("店铺商圈经纬度无效，请联系客服");
                    return orderSubmitResult;
                }
                String[] latlngs = shopInfo.getLnglats().split(";");
                Double[] lngArr = new Double[latlngs.length];
                Double[] latArr = new Double[latlngs.length];
                for (int j = 0; j < latlngs.length; j++) {
                    String[] lnla = latlngs[j].split(",");
                    lngArr[j] = Double.parseDouble(lnla[0]);
                    latArr[j] = Double.parseDouble(lnla[1]);
                }
                Boolean flag = Geohash.isInPolygon(userAddress.getLng(), userAddress.getLat(), lngArr, latArr);
                if (!flag) {
                    orderSubmitResult.setSuccess(false);
                    orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                    return orderSubmitResult;
                }
            }
        }
        if (cityAgent != null) {
            orderSubmitResult.setAgentId(cityAgent.getId());
        }
        orderSubmitResult.setOrderDeliveryPrice(deliveryPrice);
        return orderSubmitResult;
    }

    // 根绝收货地址 , 商家商圈集合 ，商圈配送敢为获取一个商圈信息
    public static CityAgent getValidCityAgent(List<Long> agentIdList, ShopInfo shopInfo, Double lng, Double lat) {
        if (agentIdList == null || shopInfo == null || ValidateUtil.isNotLatLng(lat, lng)) {
            return null;
        }
        for (Long agentId : agentIdList) {
            CityAgent cityAgent = CityAgentMemory.getInstance().getById(agentId);
            if (!Optional.ofNullable(cityAgent).map(CityAgent::getLnglats).isPresent()) {
                continue;
            }
            if (checkInCityAgentFence(shopInfo, cityAgent, lat, lng)) {
                return cityAgent;
            }
        }
        return null;
    }

    public static boolean checkInCityAgentFence(ShopInfo shopInfo, CityAgent cityAgent, Double lat, Double lng) {
        if (cityAgent == null) {
            return false;
        }
        if (!CommonUtils.isInFenceRange(cityAgent.getLnglats(), lng, lat)) {
            return false;
        }
        Integer postRange = cityAgent.getRang() == null ? 0 : cityAgent.getRang();
        if (null != shopInfo) {
//            double distinctShop = Geohash.distance(shopInfo.getLat(), shopInfo.getLng(), lat, lng);
//            if (JYMathDoubleUtils.sub(distinctShop, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
//                return false;
//            }
            return checkPostRange(shopInfo.getLat(), shopInfo.getLng(), lat, lng, postRange);
        }
        return true;
    }

    public static boolean checkPostRange(Double lat1, Double lng1, Double lat, Double lng, int postRange) {
        double distinctShop = Geohash.distance(lat1, lng1, lat, lng);
        if (JYMathDoubleUtils.sub(distinctShop, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
            return false;
        }
//        }
        return true;
    }

    // 检测是否在商圈范围内
    public static boolean checkInCityShopFence(ShopInfo shopInfo, Double lat, Double lng) {
        if (!Optional.ofNullable(shopInfo).map(a -> a.getLnglats()).isPresent()
                || !StringUtils.isEmpty(shopInfo.getLnglats())) {
            try {
                System.out.println("店铺未设置电子围栏。。。id:" + shopInfo.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }
        if (!CommonUtils.isInFenceRange(shopInfo.getLnglats(), lng, lat)) {
            return false;
        }
        return true;
    }

    //创业商圈-配送费处理
    private static OrderSubmitResult doSquareDeliveryPrice(Integer isZiQu, ShopInfo shopInfo,
                                                           UserAddress userAddress, Double deliveryPrice,
                                                           Double buyLat, Double buyLng,
                                                           OrderSubmitResult orderSubmitResult) {
        if (null != isZiQu && 0 == isZiQu) { // 需要配送
            if (ValidateUtil.isNotLatLng(shopInfo.getLat(), shopInfo.getLng())) {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("店铺位置信息不准确，请联系客服");
                return orderSubmitResult;
            }
            //验证配送范围
            if (null != userAddress) { //收货地址方式
                //配送费计算方式
                if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 2 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) { //配送费计算方式 1固定配送费 2 按距离（平台）计算 3按距离（店铺）
                    //2 按距离（平台）计算
                    if (ValidateUtil.isNotLatLng(userAddress.getLat(), userAddress.getLng())) {
                        orderSubmitResult.setSuccess(false);
                        orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                        return orderSubmitResult;
                    }
                    //验证按距离计算的配送费是否正确
                    Double distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
                    SysVariablePaotui sysVariablePaotui = SysVariablePaotuiMemory.getInstance().getByCode(7);
                    Double km = JYMathDoubleUtils.div(distance, 1000);
                    if (sysVariablePaotui != null) {
                        // 如果设置比列  则按照比例计算距离
                        if (SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
                            Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
                            distance = JYMathDoubleUtils.mul(distance, rate);
                        }
                        km = JYMathDoubleUtils.div(distance, 1000);
                        if (km - Double.parseDouble(sysVariablePaotui.getRang()) <= 0) {
                            String money = sysVariablePaotui.getVal();
                            if (ValidateUtil.isNotNull(money)) {
                                deliveryPrice = Double.parseDouble(money);
                            }
                        } else {
                            Double after = JYMathDoubleUtils.sub(km, Double.parseDouble(sysVariablePaotui.getRang()));
                            Double round = Math.ceil(after);
                            deliveryPrice = JYMathDoubleUtils.add(Double.parseDouble(sysVariablePaotui.getVal()), JYMathDoubleUtils.mul(round, Double.parseDouble(sysVariablePaotui.getPre())));
                        }
                    } else {
                        orderSubmitResult.setSuccess(false);
                        orderSubmitResult.setError("查不到配置参数");
                        return orderSubmitResult;
                    }
                } else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 3 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
                    // 3按距离（店铺）
                    if (ValidateUtil.isNotLatLng(userAddress.getLat(), userAddress.getLng())) {
                        orderSubmitResult.setSuccess(false);
                        orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                        return orderSubmitResult;
                    }

                    //验证按距离(店铺)计算的配送费是否正确
                    Double distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
                    Double km = JYMathDoubleUtils.div(distance, 1000);//距离
                    //价格计算方式：基础配送费+上取整（实际下单距离-基础范围）*超出后每公里的价格
                    //v2 店铺没有这只规则的时候，使用平台的规则
                    //withinDistance 范围
                    Double withinDistance = shopInfo.getWithinDistance();
                    //fixedCost 范围内价格
                    Double fixedCost = shopInfo.getFixedCost();
                    //oneKmCost 超出后每公里价格
                    Double oneKmCost = shopInfo.getOneKmCost();
                    if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {

                        //withinDistance 范围
                        withinDistance = 0.0d;
                        //fixedCost 范围内价格
                        fixedCost = 0.0d;
                        //oneKmCost 超出后每公里价格
                        oneKmCost = 0.0D;
                    }
                    if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                        //不收配送费
                    } else {
                        // 如果设置比列  则按照比例计算距离
                        if (SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
                            Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
                            distance = JYMathDoubleUtils.mul(distance, rate);
                        }
                        km = JYMathDoubleUtils.div(distance, 1000);
                        if (km - withinDistance <= 0) {
                            deliveryPrice = fixedCost;
                        } else {
                            Double after = JYMathDoubleUtils.sub(km, withinDistance);
                            Double round = Math.ceil(after);
                            deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
                        }
                    }
                }
            } else { //传入经纬度方式
                if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 2 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) { //配送费计算方式 1固定配送费
                    // 2按距离计算(平台)
                    if (ValidateUtil.isNotLatLng(buyLat, buyLng)) {
                        orderSubmitResult.setSuccess(false);
                        orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                        return orderSubmitResult;
                    }

                    //验证按距离计算的配送费是否正确
                    Double distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                    SysVariablePaotui sysVariablePaotui = SysVariablePaotuiMemory.getInstance().getByCode(7);
                    Double km = JYMathDoubleUtils.div(distance, 1000);

                    if (sysVariablePaotui != null) {
                        // 如果设置比列  则按照比例计算距离的费用
                        if (SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
                            Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
                            distance = JYMathDoubleUtils.mul(distance, rate);
                        }
                        km = JYMathDoubleUtils.div(distance, 1000);
                        if (km - Double.parseDouble(sysVariablePaotui.getRang()) <= 0) {
                            String money = sysVariablePaotui.getVal();
                            if (ValidateUtil.isNotNull(money)) {
                                deliveryPrice = Double.parseDouble(money);
                            }
                        } else {
                            Double after = JYMathDoubleUtils.sub(km, Double.parseDouble(sysVariablePaotui.getRang()));
                            Double round = Math.ceil(after);
                            deliveryPrice = JYMathDoubleUtils.add(Double.parseDouble(sysVariablePaotui.getVal()), JYMathDoubleUtils.mul(round, Double.parseDouble(sysVariablePaotui.getPre())));
                        }
                    } else {
                        orderSubmitResult.setSuccess(false);
                        orderSubmitResult.setError("查不到配置参数");
                        return orderSubmitResult;
                    }
                } else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 3 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
                    // 3按距离（店铺）
                    if (ValidateUtil.isNotLatLng(buyLat, buyLng)) {
                        orderSubmitResult.setSuccess(false);
                        orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                        return orderSubmitResult;
                    }

                    //验证按距离(店铺)计算的配送费是否正确
                    Double distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                    Double km = JYMathDoubleUtils.div(distance, 1000);

                    //v2 店铺没有这只规则的时候，使用平台的规则
                    //withinDistance 范围
                    Double withinDistance = shopInfo.getWithinDistance();
                    //fixedCost 范围内价格
                    Double fixedCost = shopInfo.getFixedCost();
                    //oneKmCost 超出后每公里价格
                    Double oneKmCost = shopInfo.getOneKmCost();
                    if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                        //店铺未设置规则
                        //withinDistance 范围
                        withinDistance = 0.0D;
                        //fixedCost 范围内价格
                        fixedCost = 0.0D;
                        //oneKmCost 超出后每公里价格
                        oneKmCost = 0.0D;
                    }
                    if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                        //不收配送费
                    } else {
                        if (SYS_SETTINGS.RUNNING_DISTANCE_RATE > 0) {
                            Double rate = JYMathDoubleUtils.div(SYS_SETTINGS.RUNNING_DISTANCE_RATE, 100);
                            distance = JYMathDoubleUtils.mul(distance, rate);
                        }
                        km = JYMathDoubleUtils.div(distance, 1000);
                        if (km - withinDistance <= 0) {
                            deliveryPrice = fixedCost;
                        } else {
                            Double after = km - withinDistance;
                            Double round = Math.ceil(after);
                            deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
                        }
                    }
                }
            }
        }
        orderSubmitResult.setOrderDeliveryPrice(deliveryPrice);
        return orderSubmitResult;
    }

    // 配送处理
    private static OrderSubmitResult doDeliveryPriceV3(
//            HashSet<Long> shopIdList
            ShopInfo shopInfo,
            CityAgent cityAgent,
            Integer isZiQu,
            UserAddress userAddress, Long agentId,
            Long deliveryId,
            Double deliveryPrice,
            Double buyLat, Double buyLng,
            OrderSubmitResult orderSubmitResult) {
//        if (shopIdList == null || shopIdList.size() == 0) {
//            orderSubmitResult.setSuccess(false);
//            orderSubmitResult.setError("店铺信息不能为空");
//            return orderSubmitResult;
//        }
//        if (!ValidateUtil.isID(agentId)) {
//            orderSubmitResult.setSuccess(false);
//            orderSubmitResult.setError("商圈信息不能为空");
//            return orderSubmitResult;
//        }
//        CityAgent cityAgent = CityAgentMemory.getInstance().getById(agentId);
//        if (cityAgent == null) {
//            orderSubmitResult.setSuccess(false);
//            orderSubmitResult.setError("未货到商圈信息");
//            return orderSubmitResult;
//        }
//        if (userAddress != null) {
//            buyLat = userAddress.getLat();
//            buyLng = userAddress.getLng();
//        }
//        // 经纬度
//        if (!ValidateUtil.isLatLng(buyLat, buyLng)) {
//            orderSubmitResult.setSuccess(false);
//            orderSubmitResult.setError("经纬度不能为空");
//            return orderSubmitResult;
//        }
//
//        ShopInfo shopInfo = null;
//        Map<Long, Double> shopInfoMap = new HashMap<>();
//        for (Long id : shopIdList) {
//            if (id == null) {
//                continue;
//            }
//            ShopInfo info = ShopMemory.getInstance().getShopById(id);
//            if (info == null) {
//                continue;
//            }
//            if (ValidateUtil.isLatLng(info.getLat(), info.getLng())) {
//                double distinctShop = Geohash.distance(info.getLat(), info.getLng(), buyLat, buyLng);
//                shopInfoMap.put(id, distinctShop);
//            }
//        }
//        // 使用最远的位置
//        if (!shopInfoMap.isEmpty()) {
//            Long max = getMapValueMax(shopInfoMap);
//            shopInfo = ShopMemory.getInstance().getShopById(max);
//        }
//        // 但是固定配送费还是使用商圈的
//        shopInfo.setWithinDistance(cityAgent.getWithinDistance());
//        shopInfo.setFixedCost(cityAgent.getFixedCost());
//        shopInfo.setOneKmCost(cityAgent.getOneKmCost());
        if (shopInfo == null) {
            orderSubmitResult.setSuccess(false);
            orderSubmitResult.setError("店铺信息不能为空");
            return orderSubmitResult;
        }
        if (null != isZiQu && 0 == isZiQu) { //需要配送
            if (ValidateUtil.isID(deliveryId)) {//配送
                if (null == userAddress) {
                    orderSubmitResult.setSuccess(false);
                    orderSubmitResult.setError("请核对送货地址后重试");
                    return orderSubmitResult;
                }
            }

            // 是否启用电子围栏 0.不使用电子围栏 1.使用电子围栏(商圈) 2.使用电子围栏(店铺)
            if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && (0 == 1 - SYS_SETTINGS.IS_ELECTRONIC_FENCE || 0 == 2 - SYS_SETTINGS.IS_ELECTRONIC_FENCE)) {
                orderSubmitResult = doDeliveryPriceV2(isZiQu, shopInfo,
                        userAddress, agentId,
                        cityAgent, deliveryPrice,
                        buyLat, buyLng, 0.0d,
                        orderSubmitResult);
            } else {
                orderSubmitResult = doDeliveryPrice(isZiQu, shopInfo,
                        userAddress, agentId,
                        cityAgent, deliveryPrice,
                        buyLat, buyLng,
                        0.0d,
                        orderSubmitResult);
            }
            if (null != orderSubmitResult) {
                if (orderSubmitResult.isSuccess()) {
                    deliveryPrice = orderSubmitResult.getOrderDeliveryPrice();
                } else {
                    return orderSubmitResult;
                }
            } else {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("验证配送费错误，请稍后再试");
                return orderSubmitResult;
            }
        }
        orderSubmitResult.setSuccess(true);
        return orderSubmitResult;
    }

    private static Long getMapValueMax(Map<Long, Double> map) {
        if (map == null) {
            return null;
        }
//        Double dis = -1d;
//        Long id = null;
//        int index = 0;
//        for (Long tId : map.keySet()) {
//            Double dDis = map.get(tId);
//
//            if (index == 0) {
//                id = tId;
//                dis = dDis;
//            } else {
//                if (dDis != null && dDis > dis) {
//                    id = tId;
//                    dis = dDis;
//                }
//            }
//            index++;
//        }
        List<Map.Entry<Long, Double>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, (a1, a2) -> (a2.getValue() - a1.getValue()) >= 0 ? 1 : -1);
        return list.get(0).getKey();
//        return id;
    }

    //活动处理
    private static OrderInfo doOrderGame(String submitUsername, ShopInfo shopInfo, Long gameId, Long gameRuleId, String gameInfoJson,
                                         String orderNo, OrderInfo orderInfo,
                                         Long time, Double totalMoney, OrderSubmitResult orderSubmitResult) {


        return orderInfo;
    }

    //活动处理
    private static OrderInfo doOrderDeliveryPriceGame(ShopInfo shopInfo, Long gameId, Long gameRuleId, String gameInfoJson,
                                                      String orderNo, OrderInfo orderInfo,
                                                      Long time, Double orderTotalMoney, Double mustPayMoney,
                                                      String submitUsername, Double deliveryPrice, OrderSubmitResult orderSubmitResult) {


        return orderInfo;
    }
//
//    // 微服务的使用
//    //保存红包活动信息
//    public static OrderSubmitResult saveRedPacketGameInfoV2(RedUserPacketRecordV2VO info,//微服务红包
//                                                            String orderNo, OrderInfo orderInfo, Long time,
//                                                            Double totalPrice,
//                                                            Double awardMoney, Double platformAwardMoney, Double shopAwardMoney,
//                                                            Double mustPayMoney,
//                                                            String submitUsername, String shopName) {
//        OrderSubmitResult orderSubmitResult = new OrderSubmitResult();
//
//        //获取红包信息
////        QueryCondition query = QueryCondition.getInstance();
////        Expression expression = Expression.getInstance();
////        expression.addChild("delFlag", 0);
////        expression.addChild("id", redPacketRecordId);
////        query.addCondition(expression);
////        String sql = DaoUtils.getSql(PojoTables.RED_PACKET_RECORD, query);
////        RedPacketRecord info = null;
////        try {
////            info = (RedPacketRecord) UserDaoSql.getInstance().getObject(RedPacketInfo.class, sql);
////        } catch (SQLException e) {
////            e.printStackTrace();
////        }
////        if (null == info) {
////            Order.rollBackGoods(orderNo);
////            orderSubmitResult.setSuccess(false);
////            orderSubmitResult.setError("所选红包失效，请重新选择");
////            return orderSubmitResult;
////        }
//        Double tAward = 0d;//总计优惠
//        Double pAward = 0d;//平台优惠
//        Double sAward = 0d;//商家优惠
//
////        RedPacketRecord info = RedPacketRecordMemory.getInstance().getById(redPacketRecordId);
//        if (null == info) {
//            orderSubmitResult.setSuccess(false);
//            orderSubmitResult.setError("所选红包失效，请重新选择");
//            return orderSubmitResult;
//        }
//
//        if (null == info.getIsUsed()) {
//            info.setIsUsed(0);
//        }
//        if (0 == 1 - info.getIsUsed()) {
//            orderSubmitResult.setSuccess(false);
//            orderSubmitResult.setError("所选红包已使用，请重新选择");
//            return orderSubmitResult;
//        }
//
//        if (null == info.getGameType()) {
//            info.setGameType(GAME_TYPE.MONEY_STRING);
//        }
//
//        if (BOOS_TYPE.SHOP_STRING.equals(info.getBossType()) && 0 != orderInfo.getShopId() - info.getShopId()) {
//            orderSubmitResult.setSuccess(false);
//            orderSubmitResult.setError("您选择的活动不是当前店铺的，请重新选择");
//            return orderSubmitResult;
//        }
//
////        if (time > info.getCreateTime() + 3 * 24 * 60 * 60 * 1000) {//有效期为3天
////            Order.rollBackGoods(orderNo);
////            orderSubmitResult.setSuccess(false);
////            orderSubmitResult.setError("红包有效期3天，已过期，无法使用");
////            return orderSubmitResult;
////        }
//
//        //是否满足开始结束时间
//        if (time < info.getStartTim().getTime()) {
//            orderSubmitResult.setSuccess(false);
//            orderSubmitResult.setError("活动还未开始");
//            return orderSubmitResult;
//        }
//        if (time > info.getEndTim().getTime()) {
//            orderSubmitResult.setSuccess(false);
//            orderSubmitResult.setError("红包已过期");
//            return orderSubmitResult;
//        }
//
//        //是否满足金额要求
//        if (totalPrice < info.getPriceRang()) {
//            rollBackGoods(orderNo);
//            orderSubmitResult.setSuccess(false);
//            orderSubmitResult.setError("您不满足活动要求");
//            return orderSubmitResult;
//        }
//
//        //首单判断
//        if (GAME_TYPE.FIRST_GOODS_STRING.equals(info.getGameType()) || GAME_TYPE.FIRST_MONEY_STRING.equals(info.getGameType())) {
//            //当前账号是否有
//            if (OrderInfoMemory.getInstance().hasOrder(submitUsername)) {
//                orderSubmitResult.setSuccess(false);
//                orderSubmitResult.setError("您已成功购买过商品，不满足首单活动要求");
//                return orderSubmitResult;
//            }
//        }
//        //满减金额处理
//        if (GAME_TYPE.FIRST_MONEY_STRING.equals(info.getGameType()) || GAME_TYPE.MONEY_STRING.equals(info.getGameType())) {
//            tAward = info.getPrice();
//            awardMoney = JYMathDoubleUtils.add(awardMoney, info.getPrice());
//            mustPayMoney = JYMathDoubleUtils.sub(totalPrice, awardMoney);
//
//            if (ValidateUtil.isNotAbsDouble(info.getPlatformPrice()) && ValidateUtil.isNotAbsDouble(info.getShopPrice())) {
//                switch (info.getBossType()) {
//                    case BOOS_TYPE.PLATFORM_STRING: {
//                        platformAwardMoney = JYMathDoubleUtils.add(platformAwardMoney, info.getPrice());
//                        shopAwardMoney = JYMathDoubleUtils.add(shopAwardMoney, info.getShopPrice());
//
//                        pAward = info.getPrice();
//                        sAward = info.getShopPrice();
//                    }
//                    break;
//                    case BOOS_TYPE.SHOP_STRING: {
//                        platformAwardMoney = JYMathDoubleUtils.add(platformAwardMoney, info.getPlatformPrice());
//                        shopAwardMoney = JYMathDoubleUtils.add(shopAwardMoney, info.getPrice());
//
//                        pAward = info.getPlatformPrice();
//                        sAward = info.getPrice();
//                    }
//                    break;
//                }
//            } else {
//                platformAwardMoney = JYMathDoubleUtils.add(platformAwardMoney, info.getPlatformPrice());
//                shopAwardMoney = JYMathDoubleUtils.add(shopAwardMoney, info.getShopPrice());
//
//                pAward = info.getPlatformPrice();
//                sAward = info.getShopPrice();
//            }
//        }
//        orderInfo.setAwardMoney(awardMoney);
//        orderInfo.setPlatformAwardMoney(platformAwardMoney);
//        orderInfo.setShopAwardMoney(shopAwardMoney);
//        orderInfo.setTotalPrice(mustPayMoney);//待支付金额
//        orderInfo.setTotalMoney(totalPrice);//订单总金额
//
//        String goodsName = null;
//        Double goodsPrice = null;
//        String goodsImageUrl = null;
//        String goodsDescs = null;
//        if (GAME_TYPE.GOODS_STRING.equals(info.getGameType()) || GAME_TYPE.FIRST_GOODS_STRING.equals(info.getGameType())) {
////            if (ValidateUtil.isID(info.getGoodsId())) {
////                GoodsInfo goodsInfo = GoodsMemory.getInstance().getGoodsInfo(info.getGoodsId());
////                if (null != goodsInfo) {
////                    goodsName = goodsInfo.getName();
////                    goodsPrice = goodsInfo.getPrice();
////
////                    goodsImageUrl = goodsInfo.getImageUrl();
////                    if (ValidateUtil.isNull(goodsImageUrl)) {
////                        //为空时使用商品的头像
////                        goodsImageUrl = goodsInfo.getImageUrl();
////                    }
////                    if (ValidateUtil.isNotNull(goodsImageUrl) && ValidateUtil.isNetUrl(goodsImageUrl)) {
////                        goodsImageUrl = goodsImageUrl.replace(Common.imageUrl, "");
////                    }
////
////                    goodsDescs = goodsInfo.getDescs();
////                }
////            }
//        }
//        int gameType = 0;
//        switch (info.getGameType()) {
//            case GAME_TYPE.MONEY_STRING: {//满减
//                gameType = GAME_TYPE.RED_PACKET_MONEY;
//            }
//            break;
//            case GAME_TYPE.GOODS_STRING: {//满赠
//                gameType = GAME_TYPE.RED_PACKET_GOODS;
//            }
//            break;
//            case GAME_TYPE.FIRST_MONEY_STRING: {//首单减
//                gameType = GAME_TYPE.RED_PACKET_FIRST_MONEY;
//            }
//            break;
//            case GAME_TYPE.FIRST_GOODS_STRING: {//首单赠
//                gameType = GAME_TYPE.RED_PACKET_FIRST_GOODS;
//            }
//            break;
//        }
//        int bossType  = 0;
//
//        if(BOOS_TYPE.SHOP_STRING.equals(info.getBossType())){
//            bossType = BOOS_TYPE.SHOP;
//        }else{
//            bossType = BOOS_TYPE.PLATFORM;
//        }
//
//        OrderGameRules orderGameRules = new OrderGameRules(orderNo, info.getId(), 0l, bossType, gameType,
//                info.getPriceRang(), info.getPrice(),
//                info.getStartTim().getTime(), info.getEndTim().getTime(), 1,
//                info.getFromUsername(), info.getShopId(), shopName,
//                info.getName(), info.getDescs(), info.getDescs(),
//                goodsName, 0l, goodsPrice, goodsImageUrl, goodsDescs,
//                submitUsername, time);
//        orderGameRules.setShopAward(sAward);
//        orderGameRules.setPlatformAward(pAward);
//
//        try {
//            UserDaoSql.getInstance().insertObj(PojoTables.ORDER_INFO_GAME, orderGameRules);
//        } catch (SQLException e) {
//            e.printStackTrace();
//            orderSubmitResult.setSuccess(false);
//            orderSubmitResult.setError("保存红包信息时出错，请稍后再试[" + info.getName() + "]");
//            return orderSubmitResult;
//        }
//
//
//
//
//        //添加红包记录缓存
//        OrderRedPacketRecord record = new OrderRedPacketRecord();
//        try {
//            ObjectUtils.copyPropertiesExclude(info, record, null);
//        } catch (Exception e) {
//            e.printStackTrace();
//            e.printStackTrace();
//            orderSubmitResult.setSuccess(false);
//            orderSubmitResult.setError("保存红包使用记录时出错，请稍后再试");
//            return orderSubmitResult;
//        }
//        record.setId(null);
//        record.setOrderNo(orderNo);
//        record.setRecordId(info.getId());
//        record.setRedPacketId(info.getpId());
//        record.setCreateTime(time);
//        record.setCreateUser(submitUsername);
//        record.setUpdateUser(null);
//        try {
//            UserDaoSql.getInstance().insertObj(PojoTables.ORDER_INFO_RED_PACKET, record);
//        } catch (SQLException e) {
//            e.printStackTrace();
//            e.printStackTrace();
//            orderSubmitResult.setSuccess(false);
//            orderSubmitResult.setError("保存红包使用记录时出错，请稍后再试.");
//            return orderSubmitResult;
//        }
//
//        OrderRedPacketRecordMemory.getInstance().add(orderNo);
//
//        orderSubmitResult.setSuccess(true);
//        orderSubmitResult.setOrderNo(orderNo);
//        orderSubmitResult.setOrderTotalMoney(totalPrice);
//        orderSubmitResult.setMustPayMoney(mustPayMoney);
//        orderSubmitResult.setAwardMoney(awardMoney);
//        orderSubmitResult.setPlatformAwardMoney(platformAwardMoney);
//        orderSubmitResult.setShopAwardMoney(shopAwardMoney);
//        return orderSubmitResult;
//    }

    // 第三方对接 - 获取配送费
    public static double getDaDaPostDeliveryPrice(String sysAppKey, Long addressId, Long shopId) throws Exception {
        UserAddress info = UserAddressMemory.getInstance().getAddressInfo(addressId);
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);

        if (info == null || shopInfo == null) {
            return 0.0d;
        }
        if (StringUtils.isEmpty(sysAppKey)) {
            sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
        }
        DeliveryOrderTO to = new DeliveryOrderTO();
        String address = "";
        if (ValidateUtil.isNotNull(info.getAddress())) {
            address = info.getAddress();
        }
        if (ValidateUtil.isNotNull(info.getAddress2()) && !"null".equalsIgnoreCase(info.getAddress2())) {
            address += " " + info.getAddress2();
        }
        if (ValidateUtil.isNotNull(info.getAddress3()) && !"null".equalsIgnoreCase(info.getAddress3())) {
            address += " " + info.getAddress3();
        }
        // 获取配送方式
        OrderOverTimeInfo orderDeliveryInfo = AgentOrderOverTimeMemory.getInstance().getAgentOrderOverTimeInfoByAgentId(ShopAgentRelationMemory.getInstance().getAgentByShopId(shopId));
        if (orderDeliveryInfo == null || (StringUtils.isEmpty(orderDeliveryInfo.getDeliveryType())) || orderDeliveryInfo.getDeliveryType().equals("sys")) {
            throw new Exception("店铺所属商圈未设置正确的配送方式!");
        }
        String or = getDaDaOrderNo();
        to.setProv(info.getProvince())
                .setCity(info.getCity())
                .setCounty(info.getCounty())
                .setSysCustomer(sysAppKey).setShopId(shopId + "")
                .setBuyerLng(info.getLng())
                .setBuyerLat(info.getLat())
                .setBuyerName(info.getBuyer())
                .setBuyerPhone(info.getTelephone())
                .setBuyerAddr(address)
                .setPlateform(orderDeliveryInfo.getDeliveryType())
                .setOrderNo(or).setDeliveryNo(or);
        to.setFromAddress(shopInfo.getAddress())
                .setFromLatitude(shopInfo.getLat())
                .setFromLongitude(shopInfo.getLng())
                .setFromMobile(shopInfo.getTelephone())
                .setFromSenderName(shopInfo.getShopName());
        try {
            DeliveryFeeTO deliveryFeeTO = DeliveryOrderSyncService.getInstance().getDeliverMoney(to.getPlateform(), to);
            if (deliveryFeeTO != null && deliveryFeeTO.getState() == 1) {
                return deliveryFeeTO.getDeliverFee() == null ? 0.0d : deliveryFeeTO.getDeliverFee();
            } else {
                return 0.0d;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 0.0d;
        }
    }

    public static synchronized String getDaDaOrderNo() {
        String or = DateUtils.getCurrTime() + "";
        for (int i = 0; i < 6; i++) {
            or += new Random().nextInt(10);
        }
        return or;
    }

    public static OrderSubmitResult shopSubmitOrder(ShopInfo shop, String buyName, String buyPhone, Double totalWeight, Double goodsPrice, Double buyLat, Double buyLng, String buyProvince, String buyCity, String buyCounty, String buyAddress, String buyAddress2, String buyAddress3, String note) {
        OrderSubmitResult result = new OrderSubmitResult();

        String orderNo = OrderUtils.getOrderNo();
        Long time = DateUtils.getCurrTime();
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setIsGroupOrder(0);
        orderInfo.setIsFlashSaleOrder(0);
        orderInfo.setOrderStatus(ORDER_STATUS.SHOP_SURE);

        orderInfo.setOrderType(ORDER_TYPE.SHOP_GOODS);//订单类型，商城订单
        orderInfo.setOrderNo(orderNo);
        orderInfo.setCreateTime(time);
        orderInfo.setCreateUser(shop.getOwnUsername());
        orderInfo.setTotalWeight(totalWeight);
        Long agentId = ShopAgentRelationMemory.getInstance().getAgentByShopId(shop.getId());
        orderInfo.setAgentId(agentId);

        orderInfo.setIsSeriesSaleShop(shop.getIsSeriesSale() == null ? 0 : shop.getIsSeriesSale());// 商家类型

        orderInfo.setShopId(shop.getId());
        orderInfo.setUsername(shop.getOwnUsername());
        orderInfo.setIsComment(0);//是否已评价
        orderInfo.setUserDel(0);//是否已删除 0未删，1删除

        orderInfo.setIsUrgent(0);//是否加急
        orderInfo.setNote(note);//订单备注
        orderInfo.setIsZiQu(0);
        orderInfo.setShopSelfPost(0);
        orderInfo.setTotalGoodsMoney(ValidateUtil.isAbsDouble(goodsPrice) ? goodsPrice : 0.0d);
        orderInfo.setTotalMoney(orderInfo.getTotalGoodsMoney());
        orderInfo.setTotalWeight(ValidateUtil.isAbsDouble(totalWeight) ? totalWeight : 0.0d);
        orderInfo.setPacketPrice(0.0d);
        orderInfo.setOriginalYunFei(0.0d);
        orderInfo.setOriginalYunFeiShop(0.0D);
        orderInfo.setDeliveryPrice(0.0d);
        orderInfo.setTotalPrice(orderInfo.getTotalMoney());
        orderInfo.setShopName(shop.getShopName());//店铺名称
        orderInfo.setShopNameLang(shop.getShopNameLang());// 店铺多语言
        orderInfo.setShopPhone(shop.getTelephone());//店铺电话
        orderInfo.setShopCity(shop.getCity());//店铺所在城市
        orderInfo.setShopAddress(shop.getAddress());//店铺地址
        orderInfo.setShopLat(shop.getLat());        //店铺纬度
        orderInfo.setShopLng(shop.getLng());//店铺经度
        String shopImage = shop.getImageUrl();
        if (ValidateUtil.isNetUrl(shopImage)) {
            shopImage = shopImage.replace(SYS_CONFIG_PATH.IMAGE_BASE_URL, "");
        }
        orderInfo.setShopImageUrl(shopImage);//店铺头像

        orderInfo.setBuyer(buyName);
        orderInfo.setTelephone(buyPhone);
        String address = "";
        if (ValidateUtil.isNotNull(buyAddress)) {
            address = buyAddress;
        }
        if (ValidateUtil.isNotNull(buyAddress2)) {
            address += buyAddress2;
        }
        if (ValidateUtil.isNotNull(buyAddress3)) {
            address += buyAddress3;
        }
        orderInfo.setAddress(address);
        String address2 = "";
        if (ValidateUtil.isNotNull(buyAddress2)) {
            address2 += buyAddress2;
        }
        if (ValidateUtil.isNotNull(buyAddress3)) {
            address2 += buyAddress3;
        }
        orderInfo.setAddress2(address2);
        orderInfo.setLng(buyLng);
        orderInfo.setLat(buyLat);
        orderInfo.setProvince(buyProvince);
        orderInfo.setCity(buyCity);
        orderInfo.setCounty(buyCounty);
        // 调度模式处理 2019年11月15日16:31:12 // 只有在调度优先的模式下 才会由调度到大厅内
        if (GrabOrderModeMan.getGrabOrderMode(orderInfo.getAgentId()) == GRAB_ORDER_MODE.DISPATCH_FIRST_TO_OTHER) {
            orderInfo.setDispatchState(ORDER_DISPATCH_STATE.ORDER_DISPATCH);
        }
        // 调度模式处理结束
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.OrderInfo, orderInfo);
        } catch (SQLException e) {
            System.out.println("保存订单信息失败：" + e.getMessage());
            rollBackGoods(orderNo);
            e.printStackTrace();
            result.setSuccess(false);
            result.setError("存储订单信息失败，请稍后再试");
            return result;
        }
        //4. 订单状态保存
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderNo(orderNo);
        orderStatus.setCreateUser(shop.getOwnUsername());
//        orderStatus.setOrderStatus(ORDER_STATUS.SUBMIT);
        orderStatus.setCreateTime(DateUtils.getCurrTime());
        // 线下支付
//        if (isUnderLinePay != null && 0 == isUnderLinePay - 1) {
//            orderStatusInt = ORDER_STATUS.UNDERLINE_SUBMIT;
////            orderStatus.setOrderStatus(ORDER_STATUS.UNDERLINE_SUBMIT);
//        }
        orderStatus.setOrderStatus(ORDER_STATUS.SHOP_SURE);
        // end
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
        } catch (SQLException e) {
            rollBackGoods(orderNo);
            e.printStackTrace();
            result.setSuccess(false);
            result.setError("存储订单状态信息失败，请稍后再试");
            return result;
        }

        //5 缓存
        //5.1 缓存订单信息
        OrderInfoMemory.getInstance().addOrderInfo(orderNo);
        //5.2 缓存订单商品信息
        OrderGoodsMemory.getInstance().addGoods(orderNo);
        //5.3 缓存订单状态信息
        OrderStatusMemory.getInstance().addStatus(orderNo);
        result.setSuccess(true);
        return result;
    }
}
